JSON 嵌套元素未定义

JSON Nested Elements Undefined

我在访问 JSON 数组中的嵌套值时遇到了极大的困难,而且我终究无法弄清楚为什么我的尝试会导致未定义的值。我正在尝试使用 Google 距离矩阵 API.

获取两个 post 代码之间的距离

有关完整说明,请参阅此 post 的底部。现在,我将展示执行这些操作的代码。

当用户完成输入出发地和目的地的 post代码时,将调用以下 JavaScript 函数:

function calculateDistance(){

    var origin = $("#ex_origin").val(); // Success
    var destination = $("#ex_dest").val(); // Success

    obj = { "origin" : origin, "destination" : destination   }; // Set up JSON Object
        dbParam = JSON.stringify(obj); // Convert the object into a string to be used by the PHP file

        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var result = JSON.parse(this.responseText); // Parse the JSON string so it can be read by JavaScrippt
                alert(result); // Returns JSON OBject (Expected)
                alert(result["row"][0]["elements"][0]["distance"][0].text); //Returns undefined (Undesired)

            }
        };
        xhttp.open("POST", "includes/ajax/google_maps/get_distance_info.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("obj=" + dbParam);
}

get_distance_info.php文件调用成功。它包含以下代码:

header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_POST["obj"], false);

$origin = $obj->origin;
$destination = $obj->destination;
$key = "[Removed for Stack Overflow]";

    $url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin."&destinations=".$destination."&mode=driving&language=en-EN&key=".$key;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'APIKEY: [Removed for Stack Overflow]',
        'Content-Type: application/json',
     ));
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // These were tests
    // curl_setopt($ch, CURLOPT_PROXYPORT, 3128); // These were tests
    // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // These were tests
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // These were tests
    $response = curl_exec($ch);
    curl_close($ch);
    echo $response;
    // echo json_encode($response); The result does not have to be re-encoded, as it is already encoded by the Google API.

现在,当我输入两个随机地址时,我从 get_distance_info.php 文件中得到的响应如下:

{
   "destination_addresses" : [ "Great Tower St, London EC3R 5BT, UK" ],
   "origin_addresses" : [ "Eccles, Manchester M30 0NB, UK" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "346 km",
                  "value" : 345911
               },
               "duration" : {
                  "text" : "4 hours 7 mins",
                  "value" : 14818
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

所以问题是当我们回滚到第一组JavaScript代码时,我无法获取距离的文本值,它returns未定义。但是你会注意到尝试看起来有点草率 - 这是因为我已经尝试了所有可能的变体,以至于我显然无法确定我错在哪里。

我可以确定的是,始终无法通过 "elements" 对象。好像没找到,和它有什么关系returns undefined。

拜托,因为我失去了情节;有没有人看到这段代码的问题出在哪里,我怎样才能达到预期的结果?

总结一下: 我想要 JSON 对象数组中的距离值或距离文本,但目前未定义。

P.s。对于任何想知道的人,如果我在我的 get_distance_info.php 文件中取消注释掉 json_encode,它只是 returns 作为一个字符串,因此任何迭代都是基于每个字符而不是作为一个对象。

您似乎在寻找行的第一个元素:

alert(result["row"][0]["elements"][0]["distance"][0].text); //Returns undefined (Undesired)

但是,我认为实际响应包含 'rows' 并且 distance 不是数组。

尝试:

alert(result["rows"][0]["elements"][0]["distance"].text); 

您还引用了 ["distance"][0].text) 但 "distance" 不是数组。所以你不需要在上面有索引。