2012-02-29 35 views
3

我在一個循環內發出多個AJAX請求。這裏是我的代碼爲:jQuery推遲的AJAX調用:可能的範圍問題

// set defaults 
var app_id = 'xxx'; 
var secret = 'yyy'; 
var auth_token = 'zzz'; 

// list of items to call in the API 
var insights_to_check = ['application_permission_views_top_unique', 'application_installation_adds_unique', 'application_installation_removes_unique']; 
var json_responses = {}; 

var ajax_calls = []; 

// construct the API url 
for (var i in insights_to_check) { 
    var insight = insights_to_check[i]; 
    var url = 'https://graph.facebook.com/' + app_id + '/insights/' + insight + '?' + auth_token; 
    ajax_calls.push(get_json(url, insight)); 
} 

// when all ajax requests are done, call the process function 
$.when.apply($, ajax_calls).done(function(){ 
    process_json(json_responses); 
}); 

// collect responses to the ajax request in a global object 
function get_json(url, insight) { 
    $.getJSON(url, function(json) { 
     json_responses[insight] = json; 
    }); 
} 

// show the global object 
function process_json(all_json) { 
    console.log(all_json); 
} 

的代碼有一個奇怪的問題:它運行的第一次,我可以看到AJAX請求發射和返回,但是當process_json()被調用,它會記錄undefined。如果我手動再次調用它,它將按照預期返回json。

看起來,我的延期回調在AJAX請求完成前或至少已經完成。然後才能將其響應分配給全局json_responses對象。任何人都可以在這裏看到明顯的東西嗎?

回答

2

我不知道爲什麼它會記錄undefinedit does not for me如果我省略了Ajax調用),但有一個問題與您的代碼是,.done()回調執行立即作爲ajax_calls陣列。

你必須從get_json返回$.getJSON返回值:

function get_json(url, insight) { 
    return $.getJSON(url, function(json) { 
     json_responses[insight] = json; 
    }); 
} 

這可能會解決這一問題。

+0

這的確的工作,它沒有發生在我身上,沒有返回值它不會添加任何數組。謝謝! – 2012-02-29 14:02:10