2012-02-29 36 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