如何确认当多于一个的AJAX调用完成?AJAX

2023-09-10 14:03:30 作者:爷╲拽

$(document).ready(function() {
    $("#list1").jqGrid({
        url: 'example1.php',
        /*balabala...*/
        gridComplete: function() {

        }
    });

    $("#list2").jqGrid({
        url: 'example2.php',
        /*balabala...*/
        gridComplete: function() {

        }
    });

    /*I want to do something here, but the above grids must be both complete first.*/
    Something...
});

我应该怎么办?谢谢!

How should I do ? Thanks!

推荐答案

最简单的方法就是把你的东西在 gridComplete 回调,但有两个回调检查该另一个已完成。这些方针的东西:

The easiest way is to put your "something" in the gridComplete callbacks but have the two callbacks check that the other one has finished. Something along these lines:

function do_something_wonderful() {
    // This is the awesome stuff that you want to
    // execute when both lists have loaded and finished.
    // ...
}

var one_done = false;
function done_checker() {
    if(one_done) {
        // The other one is done so we can get on with it.
        do_something_wonderful();
    }
    one_done = true;
}

$("#list1").jqGrid({
    //blah blah blah
    gridComplete: done_checker
});
$("#list2").jqGrid({
    //blah blah blah
    gridComplete: done_checker
});

这很好地扩展到两个以上的名单与一对夫妇的小改动:

This nicely extends to more than two lists with a couple small modifications:

使用 VAR how_many_done = 0; 而不是 one_done 请在 ++ how_many_done; 而不是 one_done = TRUE; ,并将其移动到顶部 done_checker 。 替换如果(one_done)如果(how_many_done == number_of_tasks),其中 number_of_tasks 是你有多少AJAX任务都有。 use var how_many_done = 0; instead of one_done. Do a ++how_many_done; instead of one_done = true; and move it to the top of done_checker. Replace the if(one_done) with if(how_many_done == number_of_tasks) where number_of_tasks is how many AJAX tasks you have.

普通版看起来有点像这样的:

The general version would look sort of like this:

var number_of_tasks = 11; // Or how many you really have.
var how_many_done   = 0;
function done_checker() {
    ++how_many_done;
    if(how_many_done == number_of_tasks) {
        // All the AJAX tasks have finished so we can get on with it.
        do_something_wonderful();
    }
}

这是更好的版本将包裹的状态下封闭:

An even better version would wrap up the state in a closure:

var done_checker = (function(number_of_tasks, run_when_all_done) {
    var how_many_done = 0;
    return function() {
        ++how_many_done;
        if(how_many_done == number_of_tasks) {
            // All the AJAX tasks have finished so we can get on with it.
            run_when_all_done();
        }
    }
})(do_something_wonderful, 11);