2017-01-25 23 views
0

我有這樣的JSON:如何在Ajax中迭代嵌套的JSON?

{ 
    "draw": 0, 
    "recordsTotal": 90, 
    "recordsFiltered": 41, 
    "data": [ 
    { 
     "id": "5", 
     "art": "default/def2.jpg", 
     "full_name": " ", 
     "title": "Hellberg - The Girl | Atomik Remix", 
     "tag": "music", 
     "time": "2015-11-14", 
     "": "" 
    }, 
    { 
     "id": "8", 
     "art": "default/def2.jpg", 
     "full_name": "Simon Deoro", 
     "title": "Tim McMorris-On (Single)", 
     "tag": "dance,popular,", 
     "time": "2015-11-14", 
     "": "" 
    }, 
    ... 
    ] 
} 

我想回到裏面data所有id的,所以我想這個功能:

function getPlaylist(id) { 
    $.ajax({ 
     type: "GET", 
     url: baseUrl+"/playlist.php?id="+id, 
     cache: false, 
     success: function(result) { 
      var samples = JSON.parse(result); 
      for (i in samples) 
      { 
       console.log(samples.data[i].id + "<br />"); 
      } 
     } 
    }); 
} 

但是我看到控制檯此錯誤

Uncaught TypeError: Cannot read property 'id' of undefined

我也試過這個for循環(控制檯的語法錯誤)

for(var i = 0; i < samples.data.length; i++) 
{ 
    var product = samples.data[i]; 
    var productId = product.id; 
    console.log(productId); 
} 

我要的是輸出5, 8(我id的)

我不是很熟悉JSON,所以我怎麼能訪問和遍歷我的結構是否正確?

+0

的可能的複製[如何遍歷一個JSON結構?](http://stackoverflow.com/questions/1078118/how-do-i-iterate-over-a-json-structure) – Ryan

回答

1

samples需求是samples.data

function getPlaylist(id) { 
    $.ajax({ 
     type: "GET", 
     url: baseUrl+"/playlist.php?id="+id, 
     cache: false, 
     success: function(result) { 
      var samples = JSON.parse(result); 
      for (i in samples.data) 
      { 
       console.log(samples.data[i].id + "<br />"); 
      } 
     } 
    }); 
} 
+0

從控制檯我看到'未捕獲的SyntaxError:意外的令牌ü在JSON在位置0' – NineCattoRules

+0

是的,對不起。我告訴過你了。我只是修復它。 – byumark

+0

現在我看到'未捕獲的SyntaxError:意外的令牌<位於JSON的位置1' – NineCattoRules

1

您可以嘗試使用map函數將數組轉換爲另一個數組。

var dataJSON = { 
 
     "draw": 0, 
 
     "recordsTotal": 90, 
 
     "recordsFiltered": 41, 
 
     "data": [ 
 
     { 
 
      "id": "5", 
 
      "art": "default/def2.jpg", 
 
      "full_name": " ", 
 
      "title": "Hellberg - The Girl | Atomik Remix", 
 
      "tag": "music", 
 
      "time": "2015-11-14", 
 
      "": "" 
 
     }, 
 
     { 
 
      "id": "8", 
 
      "art": "default/def2.jpg", 
 
      "full_name": "Simon Deoro", 
 
      "title": "Tim McMorris-On (Single)", 
 
      "tag": "dance,popular,", 
 
      "time": "2015-11-14", 
 
      "": "" 
 
     }, 
 
     
 
     ] 
 
    }; 
 
     
 

 
var obj = dataJSON.data.map((currentValue) => currentValue.id); 
 
console.log(obj);
在AJAX功能,可以代替這樣的代碼

function getPlaylist(id) { 
    $.ajax({ 
     type: "GET", 
     url: baseUrl+"/playlist.php?id="+id, 
     cache: false, 
     success: function(result) { 
      var samples = JSON.parse(result); 
      var idArray = samples.data.map(x => x.id); 
      console.log(idArray); 
     } 
    }); 
+0

你能告訴我如何在我的Ajax請求上做到這一點? – NineCattoRules

+1

更新了答案。 – Agalo