Javascript 未定义JSON嵌套元素

Javascript 未定义JSON嵌套元素,javascript,php,jquery,json,google-distancematrix-api,Javascript,Php,Jquery,Json,Google Distancematrix Api,我在访问JSON数组中的嵌套值时遇到了极大的困难,而且我一生都无法理解为什么我的尝试会导致未定义的值。我正在尝试使用谷歌距离矩阵API获取两个邮政编码之间的距离 有关详细说明,请参阅本文底部。现在,我将展示执行这些操作的代码 当用户完成输入始发地和目的地的邮政编码时,将调用以下JavaScript函数: function calculateDistance(){ var origin = $("#ex_origin").val(); // Success var destina

我在访问JSON数组中的嵌套值时遇到了极大的困难,而且我一生都无法理解为什么我的尝试会导致未定义的值。我正在尝试使用谷歌距离矩阵API获取两个邮政编码之间的距离

有关详细说明,请参阅本文底部。现在,我将展示执行这些操作的代码

当用户完成输入始发地和目的地的邮政编码时,将调用以下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);
}
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.
{
   "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"
}
已成功调用get_distance_info.php文件。它包含以下代码:

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);
}
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.
{
   "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"
}
现在,当我输入两个随机地址时,我从get\u distance\u info.php文件得到的响应如下:

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);
}
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.
{
   "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代码时,我无法获得距离的文本值,它返回未定义的值。但是你会注意到这种尝试看起来有点草率——这是因为我已经尝试了所有可能的变化,以至于我无法确定我错在哪里

我能确定的是,我始终无法通过“元素”对象。它似乎找不到它,与它相关的任何东西都返回未定义

求你了,因为我失去了情节;有人知道这段代码的问题在哪里吗?我如何才能达到预期的结果

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


另外,如果有人想知道,如果我在get_distance_info.php文件中取消注释json_encode,它将以字符串的形式返回,因此任何迭代都是以每个字符为基础进行的,而不是以对象的形式进行的。

看起来您正在查找行的第一个元素:

alert(result["row"][0]["elements"][0]["distance"][0].text); //Returns undefined (Undesired)
但是,我认为实际响应包含“行”,距离不是数组

尝试:


您还引用了[“距离”][0]。文本),但“距离”不是数组。所以你不需要在上面有一个索引。

经过这么多的努力,这确实令人尴尬。我用了你指出的那个错误和一个小小的改变来看看我哪里出了错。请将答案更新为:警报(结果[“行”][0][“元素”][0][“距离”]。文本);我可以接受!非常感谢你指出这一点。谢谢,是的,我找到了我在给SteveP的评论中提到的那个。谢谢你的贡献!