jquery - 从 API 获取数据并在浏览器上显示结果
问题描述
我正在使用 jQuery 从 HTML 输入字段中获取值,将这些值作为变量传递给 PHP 文件,该文件将在连接到 API 时将它们作为 URL 中的参数接受。
我想要实现的是,当用户输入的纬度和经度值与从 API 获得的数据不匹配时,它会要求他们输入另一个值,否则它将返回与输入的值匹配的地址。
来自 API 的数据如下:
{"address":{"adminCode2":"0363","adminCode1":"07","lng":"4.88132","distance":"0.02","lat":"52.35792"}}
HTML代码是:
Latitude: <input type="text" id="latitude" name="latitude" placeholder="52.358">
Longitude: <input type="text" id="longitude" name="longitude" placeholder="4.881">
jQuery代码:
$.ajax({
type: "POST",
url: "libs/php/getAddress.php",
dataType: "json",
data: {
latitude: $("#latitude").val(),
longitude: $("#longitude").val(),
},
success: function (result, status, xhr) {
console.log(result);
if ($("#latitude").val() == result.address.lat && $("#longitude").val() == result.address.lng){
$("#result").html(
"Address: " +
result.address.houseNumber +
" " +
result.address.street +
"<br>" +
result.address.locality +
"<br>" +
result.address.postalcode
);
} else {
$("#result").html("There are no nearest street or address with the given latitude & longitude. Please enter another value");
}
},
PHP 代码
<?php
$latitude=$_POST['latitude'];
$longitude=$_POST['longitude'];
$url = "http://api.geonames.org/addressJSON?lat=".$latitude."&lng=".$longitude."&username=username";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if($e = curl_error($ch)) {
echo $e;
}
else {
$decoded = json_decode($response, true);
// print "<PRE>";
// print_r($decoded);
$encoded = json_encode($decoded);
echo ($encoded);
}
curl_close($ch);
当我运行上面的代码时,如果输入的值不在数据中,我会在控制台中收到这些错误,但如果我输入正确的值,它将显示地址:
{status: {…}}
status: {message: "missing parameter lat", value: 14}
Uncaught TypeError: Cannot read property 'lat' of undefined
解决方案
您必须通过检查成员是否存在来检查返回的数据是否有效。
// Check if the members exist for whichever members you want to access
if(result != null && result.address != null && result.address.lat != null)
{
}
推荐阅读
- c++ - 使用 CMake 生成自定义头文件
- asp.net-core - 客户端拨打电话时如何识别用户?
- swift - 溢出运算符的效率是否低于执行不会导致溢出的操作?
- javascript - 如何在 Angular 中动态填充下拉列表(Syncfusion Scheduler)
- typescript - vue composition api“参考或反应”是否在模板上具有深度反应?
- python - 循环遍历 csv 文件中以该列表中的元素开头的列中的关键字列表 - Python
- javascript - 从嵌套数组和嵌套对象数组中过滤对象数组
- c++ - 如何创建可变数量的线程?
- react-native - React Native Error Advice - 开发服务器返回响应错误代码:500
- python - 如何抑制python中的try except block打印出的错误