首页 > 解决方案 > 从 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

标签: jqueryajaxphp-curl

解决方案


您必须通过检查成员是否存在来检查返回的数据是否有效。

// Check if the members exist for whichever members you want to access

if(result != null && result.address != null && result.address.lat != null)
{

}

推荐阅读