2013-05-05 92 views
0

我已經與Last.fm API玩耍和JSON,我一直在試圖通過一個月的過去12個月來獲取用戶的頂級藝術家。我試圖設置一個for循環來遍歷每個月,然後提取與該月相對應的相關JSON數據,但從我可以告訴它看來,for循環運行得比JSON調用快得多。如何與檢索多個JSON對象的for循環在JavaScript

我使用費利克斯布倫斯last.fm的JavaScript API https://github.com/fxb/javascript-last.fm-api

我檢查控制檯並記錄除12,我也越來越未捕獲的引用錯誤「JSON ##無月的數值。 ......沒有定義」

我試圖尋找周圍的解決方案,但我所有的搜索結果想出瞭如何通過API調用的結果,而循環我正在尋找如何編寫一個循環,多重檢索JSON對象。

<script type="text/javascript"> 

    var apiKey = "b0da1774db3d010f62b11f67c4de0667"; 
    var secret = "0baa4b10c807acc847128599680679a7"; 

    var lastfm = new LastFM({ 
    apiKey : apiKey, 
    secret : secret, 
    cache : undefined 
    }); 

    var lastfm_2 = new LastFM({ 
    apiKey : apiKey, 
    secret : secret, 
    cache : undefined 
    }); 

    $(document).ready(function() { 
    $("#submit").click(function() { 
     var username = $("#username").val(); 
     var text = ""; 
     if (username) { 
     $("#title").html("Your Most Played Artist by Month"); 
     $("#title").css("color", "#222"); 
     // Get top artists for each month 
     var topArtistsByMonth = new Array(); 
     for (var month = 0; month < 12; month++) { 
      lastfm.user.getTopArtists({user: username, period: "1month", limit: 15, page: month + 1}, {success: function(data) { 
      topArtistsByMonth.push(data.topartists); 
      console.log("Month " + month + ": " + data.topartists); 
      }}); 
     } 
     } else { 
     alert("No username"); 
     } 
    }); 
    }); 

</script> 

任何幫助將不勝感激,謝謝!

+0

你包括[http://www.json.org/json2.js](http://www.json.org/json2.js)在您的網頁上的腳本? – soulcheck 2013-05-05 02:15:27

+0

@soulcheck:現代瀏覽器具有內置的「JSON」全局。我懷疑(可能)缺乏'json2.js'是問題所在。 – icktoofay 2013-05-05 02:27:37

+0

@icktoofay該錯誤消息OP判斷得到它可能 – soulcheck 2013-05-05 02:28:44

回答

2

getTopArtists是異步的,所以調用它只有開始的請求;它不會等待它完成。回調是你知道什麼時候完成的。這意味着您的for循環會並行啓動它們,然後在完成時收集結果。但是,因爲他們可以以任何順序完成,所以不保證任何順序。爲了解決這個問題,你可能會想,使其使用明確的指標,而不是使用push

for(var month = 0; month < 12; month++) { 
    // We need to use an anonymous function to capture the current value of month 
    // so we don't end up capturing the reference to month that the for loop is 
    // using (which, by the time the callbacks complete, will always be 12.) 
    (function(month) { 
     lastfm.user.getTopArtists({user: username, period: "1month", limit: 15, page: month + 1}, {success: function(data) { 
      topArtistsByMonth[month] = data.topartists; 
      console.log("Month " + month + ": " + data.topartists); 
     }}); 
    })(month); 
} 

如果你想知道當所有的數據已被下載,你需要另一個變量保持跟蹤到目前爲止已經完成了多少項。每次調用回調函數時,都需要增加該回調函數,看它是否已經達到12。當它有,所有的數據已被下載。

+0

非常感謝!感謝您的解釋,這真的很有幫助。 – Dennis 2013-05-05 20:21:46