2012-01-23 32 views
0

可能重複:
Return value from ajax call?
JavaScript asynchronous return value/assignment with jQuery

我有一個問題,我試圖在JavaScript中迭代一個數組,但由於某種原因,它沒有這樣做。我正在用last.fm的API在$ .get()回調中創建數組,並創建一個對象數組。然後,當我嘗試迭代數組後,它不起作用,長度爲零。

我已經發布了的jsfiddle這裏:

http://jsfiddle.net/MMps2/2/

有什麼想法?我在這裏有點生氣!

注:彈出你的JS控制檯 - 我記錄的東西吧...

+1

你不能指望一個異步設置以這樣的工作。在完成API調用之前,不會構建「結果」對象。然而,圍繞'$ .get()'的代碼不會等待這種情況發生。 – Pointy

+0

數據雖然是正確的文檔對象?我想我可以通過$()爲了查詢它? –

+0

哦,對不起,混淆了'console.log'輸出。 –

回答

3

$.get請求異步運行。你試圖在結果有機會執行之前返回結果的價值。相反,當獲取請求完成時,使用回調模式來調用另一個函數。

編輯:例:

// Fetch top artists for the passed in username 
$.get('http://ws.audioscrobbler.com/2.0/', {method: 'user.getTopArtists', user: user, api_key: 'c2c920e0749f24f2661d54614335748d'}, function(data) { 

    // No need to use your higher scope results variable anymore 
    var results = []; 

    $('artist', data).each(function(index, artist) { 

     // For each artist in the result, build an object containing the artists name and MusicBrainz ID 
      results.push({ 
       'name': $('name', artist).text(), 
       'mbid': $('mbid', artist).text() 
     }); 

    }); 

    // Here's where such a call would go 
    sendResultsToWhateverObjectNeedsThem(results); 

}); 
+0

啊,是的,這是有道理的。我知道$ .get是異步的,但我一直盯着它幾個小時,看不到它!我希望它是一個很好的通用函數,因此我想要「返回」結果。我現在已經改變它,以便原始函數在可以指定回調的地方使用額外的參數。 感謝您的幫助! –