Javascript 我无法通过AJAX获得嵌套的JSON结果
我试着按照多个指南来做这件事,但没有一个是有效的。我还尝试在现有函数中添加一个Javascript 我无法通过AJAX获得嵌套的JSON结果,javascript,jquery,json,ajax,Javascript,Jquery,Json,Ajax,我试着按照多个指南来做这件事,但没有一个是有效的。我还尝试在现有函数中添加一个$。每个-函数都没有成功。这就是我的JSON结果的样子(它只是一个片段,直接复制到这里可能会被破坏,但你明白了): 我可以从“路径id”获取数据,但不能从“跟踪位置”获取数据,代码如下: $.getJSON(url, function(data){ $.each(data.loc,function(i,emp){ var a = this.path_id;
$。每个-函数都没有成功。这就是我的JSON结果的样子(它只是一个片段,直接复制到这里可能会被破坏,但你明白了):
我可以从“路径id”获取数据,但不能从“跟踪位置”获取数据,代码如下:
$.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
});
});
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);
});
});
});
当我做控制台时。log(b);,系统响应如下错误:
tringhar.html:36 Uncaught TypeError: Cannot read property 'trace_location' of undefined
我希望能够从“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
});
});
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;
-它起作用了
在您的示例中,它崩溃的原因不是因为console.log(b)
语句,而是因为您试图从未定义的位置访问trace\u位置。从代码中删除var c
和console.log(c)
语句。下面是一个使用它的示例。json的其余部分可能有其他问题,或者您的一个对象实际上没有您试图在json提要中访问的属性。例如,place
在json中没有trace\u位置
var data = {
"loc": [{
"path_id": "Trail1",
"places": [{
"way_distance": 2,
"trace_location": {
"lat": 51.2383342365623,
"lng": 20.265387296676636
},
"trace_info": "",
"way_name": ""
}]
}]
};
data.loc.forEach(function(item) {
console.log(item);
item.places.forEach(function(place){
console.log(place);
});
});
我是以“VarB”为例这样做的,但它不起作用。“var b”或“var c”在代码段中都不起作用。使用CodePenI编辑的我的帖子进行了更新-即使使用了您的代码段的精确副本,我也收到了错误消息:Uncaught TypeError:无法读取未定义的属性“trace_location”查看JSON。查看数组中只有前两项设置了位置
?这意味着,this.places[0]
可以是未定义的,在尝试访问它之前,您必须检查它是否确实存在。例如,doif(this.places.length){console.log(this.places[0].place_position);}
。我已经用安全装置更新了密码笔。