在ajax循环get完成后运行一个函数

时间:2015-07-29 18:39:23

标签: javascript jquery ajax

我使用ajax获取googlemap的点数组,除了我需要在最终$.get完成后调用MarkerClusterer之外,它还可以正常工作。

如果我只是将代码放在for循环之后,那么它会在排队完成之前运行并且无法正常工作。

如果我在$.get上使用回调,那么它将在每个循环上运行,这不是我想要的

代码

for (i = 1; i <= <?=$pages;?>; i++) {

    points = [];

    $.get("/mappoints/" + i + "/true", function(data) {

        $.each(data.json_array, function(index, value){

            //do things with data
        });
    }, "json");         
}

//run this code after the queued `$.get`s have **all** completed
console.log("done");
var markerCluster = new MarkerClusterer(map, markers);

我已经在for内尝试了以下内容,但这种情况甚至没有发生,不太清楚为什么会这样做?

if(i == <?=$pages;?>){
    var markerCluster = new MarkerClusterer(map, markers);
    console.log("done");
}

2 个答案:

答案 0 :(得分:2)

使用$ .when和.then

$.when(
// Deferred object (probably Ajax request),

// Deferred object (probably Ajax request),

// Deferred object (probably Ajax request)

).then(function() {

// All have been resolved (or rejected), do your thing

});

答案 1 :(得分:2)

只需跟踪完成的数量,以及完成所有操作后,运行您的代码。另外,不要忘记var您的变量以防止全局泄漏。

var points, counter = 0, i;
for (i = 1; i <= <?=$pages;?>; i++) {
    points = [];

    $.get("/mappoints/" + i + "/true", function(data) {

        $.each(data.json_array, function(index, value){

            //do things with data

        });
        counter++;
        if (counter === <?=$pages;?>) {
            console.log("done");
            var markerCluster = new MarkerClusterer(map, markers);
        }
    }, "json");

}

更好的选择可能是收集一系列承诺并将其应用于$.when()

var points, promises =  [], i;
for (i = 1; i <= <?=$pages;?>; i++) {
    points = [];

    promises.push($.get("/mappoints/" + i + "/true", function(data) {

        $.each(data.json_array, function(index, value){

            //do things with data

        });

    }, "json"));

}
$.when.apply(null, promises).done(function () {
    console.log("done");
    var markerCluster = new MarkerClusterer(map, markers);
});