如何确认多个 AJAX 调用已完成?

2023-12-07

$(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...
});

我应该怎么做 ?谢谢!


最简单的方法是将你的“东西”放入gridComplete回调,但让两个回调检查另一个回调是否已完成。沿着这些思路:

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
});

通过一些小的修改,这可以很好地扩展到两个以上的列表:

  • use var how_many_done = 0;代替one_done.
  • Do a ++how_many_done;代替one_done = true;并将其移动到顶部done_checker.
  • 更换if(one_done) with if(how_many_done == number_of_tasks) where number_of_tasks是您有多少个 AJAX 任务。

通用版本看起来有点像这样:

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();
    }
}

更好的版本会将状态包装在闭包中:

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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何确认多个 AJAX 调用已完成? 的相关文章