【问题标题】:How to confirm when more than one AJAX call has completed?如何确认多个 AJAX 调用何时完成?
【发布时间】:2011-05-09 04:14:55
【问题描述】:
$(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...
});

我该怎么办?谢谢!

【问题讨论】:

    标签: ajax jquery jqgrid


    【解决方案1】:

    最简单的方法是将您的“某事”放在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
    });
    

    这很好地扩展到两个以上的列表,并进行了一些小的修改:

    • 使用var how_many_done = 0; 而不是one_done
    • 使用++how_many_done; 代替one_done = true; 并将其移动到done_checker 的顶部。
    • if(one_done) 替换为if(how_many_done == number_of_tasks),其中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);
    

    【讨论】:

    • @Cynial:我添加了另一个隔离额外状态的更新,不过可能有点多。
    • 别这样说话,对我有帮助! :)
    • @Cynial:我刚刚添加了另一个可能有用的选项,或者它可能比您需要的更多保护/聪明(即“有点多”)。很高兴能提供帮助。
    【解决方案2】:

    您当前应该使用jquery deferred objects

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      • 2017-03-19
      • 2020-10-19
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      相关资源
      最近更新 更多