javascript – JSON嵌套元素未定义
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – JSON嵌套元素未定义,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3457字,纯文字阅读大概需要5分钟。
内容图文
![javascript – JSON嵌套元素未定义](/upload/InfoBanner/zyjiaocheng/789/99d8964ae6a34f2b9cfd1fde4bbd3444.jpg)
我在访问JSON数组中的嵌套值时遇到了极大的困难,并且在我的生活中无法弄清楚为什么我的尝试导致了未定义的值.我正在尝试使用Google Distance Matrix 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);
}
已成功调用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代码时,我无法得到距离的文本值,它返回undefined.但是你会注意到这个尝试看起来有点草率 – 这是因为我已经尝试了所有可以想象的变化,到目前为止,我显然无法确定我的错误.
我可以确定的是,始终如一,我无法超越“元素”对象.它似乎找不到它,与它有关的任何东西都返回undefined.
拜托,因为我正在失去情节;有谁知道这个代码的问题在哪里,以及我如何能够达到预期的效果?
总结一下:
我想要距离的值或JSON对象数组中的距离文本,但我目前正在未定义.
附:对于任何想知道的人,如果我取消注释json_encode,在我的get_distance_info.php文件中,它只是以字符串形式返回,因此任何迭代都是基于每个字符而不是作为对象完成的.
解决方法:
看起来你正在寻找行的第一个元素:
alert(result["row"][0]["elements"][0]["distance"][0].text); //Returns undefined (Undesired)
但是,我认为实际响应包含’行’而距离不是数组.
尝试:
alert(result["rows"][0]["elements"][0]["distance"].text);
内容总结
以上是互联网集市为您收集整理的javascript – JSON嵌套元素未定义全部内容,希望文章能够帮你解决javascript – JSON嵌套元素未定义所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。