我正在尝试完成一个项目,该项目要求我使用 Geonames API 来显示用户在网页搜索框中输入的任何国家/地区的信息。控制台中的 API 仅显示为空,我不知道为什么。有人可以帮忙吗?
蒂亚
$('#btnRun').click(function() {
$.ajax({
url: "libs/countryInfo.php",
type: 'GET',
dataType: 'json',
data: {
country: $('#country').val(),
},
success: function(result) {
console.log(result);
if (result && result.status && result.status.name === "ok") {
$('#txtCapital').html(result.data.capital);
$('#txtPopulation').html(result.data.population);
$('#txtCurrency').html(result.data.currency);
$('#txtLanguage').html(result.data.language);
$('#txtCoordinates').html(result.data.coordinates);
$('#countryInfoResults').show();
} else {
// Handle other cases, e.g., display an error message
console.error("Error:", result.status.description);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error("AJAX Error:", textStatus, errorThrown);
}
});
});
PHP
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
$executionStartTime = microtime(true);
$url = 'http://api.geonames.org/countryInfoJSON?formatted=true&country=' . $_REQUEST['country'] . '&username=susan.alexander&style=full';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
// Checks if 'country' parameters is provided
if (!isset($_REQUEST['country'])) {
// Handle the case where any of the parameters are missing
$output['status']['code'] = "400";
$output['status']['name'] = "Bad Request";
$output['status']['description'] = "Country parameter is missing";
$output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
$output['data'] = $decode['country'];
echo json_encode($output);
exit();
}
echo $result;
我尝试了很多方法来让它发挥作用,我在这里读到了我尝试过的类似问题和解决方案。和谷歌,但没有任何效果。我认为这与我在 JavaScript 文件中调用信息的方式有关,但我可能完全错了
建议从选择字段发送国家/地区的短代码。
<select name="country" id="country">
<option value="us">usa</option>
<option value="NP">Nepal</option>
<option value="pa">Panama</option>
</select>
<button id="btnRun">search Country</button>
<script>
$('#btnRun').click(function() {
$.ajax({
url: "countryInfo.php",
type: 'GET',
dataType: 'json',
data: {
country: $('#country').val(),
},
success: function(result) {
console.log(result);
if (result && result.status && result.status.name === "ok") {
$('#txtCapital').html(result.data.capital);
$('#txtPopulation').html(result.data.population);
$('#txtCurrency').html(result.data.currency);
$('#txtLanguage').html(result.data.language);
$('#txtCoordinates').html(result.data.coordinates);
$('#countryInfoResults').show();
} else {
// Handle other cases, e.g., display an error message
console.error("Error:", result.status.description);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error("AJAX Error:", textStatus, errorThrown);
}
});
});
</script>