2016-04-11 35 views
1

我试图按照关于如何做到这一点的多个指南 - 但没有任何工作。我也尝试在现有的内部添加$.each功能,但没有成功。这是我的JSON结果是什么样子(这只是一个片段的时候,这里直接复制,可能会被打破,但你明白了吧):我无法通过AJAX获取嵌套的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”,使用此代码:

tringhar.html:36 Uncaught TypeError: Cannot read property 'trace_location' of undefined 

我希望能够输出:

$.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),所述体系具有以下错误响应来自“trace_location”的数据没有它是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); 
       }); 



      }); 

}); 

回答

1

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 cconsole.log(c)声明。

+0

我以“var b”为例,但它不起作用。代码片段中没有“var b”或“var c”。 – Jeramo

+0

更新与CodePen –

+0

我编辑我的职位 - 即使您的代码段的精确副本,我收到错误消息:遗漏的类型错误:无法读取属性“trace_location”的未定义 – Jeramo

0

这是一个jsfiddle与它的工作。 json的其余部分还有其他问题,或者其中一个对象实际上并没有您尝试在json提要中访问的属性。例如place在json中没有trace_location

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); 
    }); 
});