【问题标题】:Fetching data from API and displaying results on browser从 API 获取数据并在浏览器上显示结果
【发布时间】:2021-03-07 16:06:10
【问题描述】:

我正在使用 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

【问题讨论】:

  • 我认为您缺少数据的属性。 result.data.address 对吧?

标签: jquery ajax php-curl


【解决方案1】:

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

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

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

}

【讨论】:

    猜你喜欢
    • 2020-09-23
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多