你$.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);
});
你不能指望一個異步設置以這樣的工作。在完成API調用之前,不會構建「結果」對象。然而,圍繞'$ .get()'的代碼不會等待這種情況發生。 – Pointy
數據雖然是正確的文檔對象?我想我可以通過$()爲了查詢它? –
哦,對不起,混淆了'console.log'輸出。 –