我尝试遵循多个有关如何执行此操作的指南 - 但没有一个有效。我还尝试在现有函数中添加 $.each
函数,但没有成功。这就是我的 JSON 结果的样子(它只是一个片段,直接复制到这里可能会损坏,但你明白了):
{
"loc": [
{
"path_id": "Trail1",
"places": [
{
"way_distance": 2,
"trace_location": {
"lat": 51.2383342365623,
"lng": 20.265387296676636
},
"trace_info": "",
"way_name": ""
}
]
}
]
}
我可以使用以下代码从“path_id”获取数据,但不能从“trace_location”获取数据:
$.getJSON(url, function(data){
$.each(data.loc,function(i,emp){
var a = this.path_id;
console.log(a); //works
var b = this.places[0].trace_location;
var c = this.places.trace_location;
console.log(b); //seems to output objects, but then crashes
console.log(c); //output is undefined
});
});
当我执行 console.log(b); 时,系统响应以下错误:
tringhar.html:36 Uncaught TypeError: Cannot read property 'trace_location' of undefined
我希望能够从“trace_location”输出数据,而不会未定义
或出现错误。谢谢。
编辑:
仍然无法使用此代码:
var url = 'https://forward-byte-711.appspot.com/read/Test/Development/en';
$(function(){
$.getJSON(url, function(data){
$.each(data.paths,function(i,emp){
var b = this.places[0].place_position;
console.log(b);
});
});
});
最佳答案
places
是一个数组。
var c = this.places.trace_location;
需要
var c = this.places[0].trace_location;
Here's a CodePen with the example - 正在运行
在您的示例中崩溃的原因不是因为 console.log(b)
语句,而是因为您尝试从未定义的位置访问 trace_location
。从代码中删除 var c
和 console.log(c)
语句。
关于javascript - 我无法通过 AJAX 获取嵌套 JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36558034/