2016-11-25 39 views
0

我使用json和jQuery從Instagram中提取圖像。通過json與多個陣列循環訪問

json數據包含對象和數組。不知何故,我不能通過第二個數組循環到我需要的值。

這是我的代碼:

var request = "./myapi.php?user=jamieoliver"; //&callback=myFunction 
$.ajax({ 
    cache: false, 
    dataType: "json", // or "jsonp" if we enabled it 
    url: request, 
    success: function(response) { 
    console.log(response); 
    for (var i = 0; i < response.entry_data.ProfilePage.length; i++) { 
     console.log(response.entry_data.ProfilePage[i].user.media.nodes[i].thumbnail_src); 
    } 
    }, 
    error: function(xhr, status, error) {} 
}); 

問題作用似乎在這裏:nodes[i] - 節點[]是一個數組 - 和我的代碼不通過它不是循環 - 它只是給了我裏面的值節點[]中的第一個對象。如何循環遍歷節點[]以獲取每個對象內部的值thumbnail_src

我沒有實時數據,但這裏的JSON響應結構的截圖:enter image description here

+2

請始終發佈*代碼*如果可以,請勿圖片。 – Jim

+0

我寧願說更好的選擇是使用高級或for循環的對象。 –

回答

4

事情是這樣的:

var request = "./myapi.php?user=jamieoliver"; //&callback=myFunction 
$.ajax({ 
    cache: false, 
    dataType: "json", // or "jsonp" if we enabled it 
    url: request, 
    success: function(response) { 
    console.log(response); 
    for (var i = 0; i < response.entry_data.ProfilePage.length; i++) { 
     for (var j = 0; j < response.entry_data.ProfilePage[i].user.media.nodes.length; j++) { 
      console.log(response.entry_data.ProfilePage[i].user.media.nodes[j].thumbnail_src); 
     } 
    } 
    }, 
    error: function(xhr, status, error) {} 
}); 
+0

男人,它的作品。非常感謝。 :-) – Meek

1

你應該循環再利用另一個for

var request = "./myapi.php?user=jamieoliver"; //&callback=myFunction 
$.ajax({ 
    cache: false, 
    dataType: "json", // or "jsonp" if we enabled it 
    url: request, 
    success: function(response) { 
    console.log(response); 
    var nodes; 
    for (var i = 0; i < response.entry_data.ProfilePage.length; i++) { 
     nodes = response.entry_data.ProfilePage[i].user.media.nodes; 

     for (var n = 0; n < nodes.length; n++) { 
     console.log(nodes[n].thumbnail_src); 
     } 
    } 
    }, 
    error: function(xhr, status, error) {} 
}); 
+0

該死的,我花了太多時間回答。那麼,我建議一個更清潔的方法來循環使用'var nodes'的第二'for'',這樣你就可以更快地閱讀和理解它。 – xWaZzo

+0

這個也很有用。但是不可能創建某種函數來自動循環遇到的每個數組嗎?我的意思是,所以我們不必使用多個for循環? – Meek

+0

@Meek這是一個很好的問題。我已經在PHP中完成了這個工作,但它必須是JavaScript中類似的東西。你必須創建一個函數來循環它找到的每個數組/對象,然後在它自己內部運行該函數,如果它找到另一個數組/對象的話。但是我不能認爲我們怎麼能使用它,因爲在你的例子中你正在尋找一個特定的對象'entry_data.ProfilePage [i] .user.media.nodes'。 – xWaZzo