Jquery 从API获取数据并在浏览器上显示结果
我使用jQuery从HTML输入字段获取值,将这些值作为变量传递给PHP文件,当连接到API时,PHP文件将接受它们作为URL中的参数 我试图实现的是,当用户输入的纬度和经度值与从API获得的数据不匹配时,它将要求他们输入另一个值,否则它将返回与输入值匹配的地址 API中的数据如下所示:Jquery 从API获取数据并在浏览器上显示结果,jquery,ajax,php-curl,Jquery,Ajax,Php Curl,我使用jQuery从HTML输入字段获取值,将这些值作为变量传递给PHP文件,当连接到API时,PHP文件将接受它们作为URL中的参数 我试图实现的是,当用户输入的纬度和经度值与从API获得的数据不匹配时,它将要求他们输入另一个值,否则它将返回与输入值匹配的地址 API中的数据如下所示: {"address":{"adminCode2":"0363","adminCode1":"07","
{"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">
您必须通过检查成员是否存在来检查返回的数据是否有效
// Check if the members exist for whichever members you want to access
if(result != null && result.address != null && result.address.lat != null)
{
}
我认为您缺少数据的属性。result.data.address,对吗?
<?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)
{
}