繁体   English   中英

如何确保所有ajax调用后我的函数都能执行?

[英]How to make sure my function executes after all ajax calls?

我有一个javascript函数。在此函数中,我有3个ajax调用。 这些ajax调用完成后,如何确保我的另一个函数执行?

function a(){
    for(var i=0;i<3;i++)
        $.post("somePage.php").done(function(){
            do stuff here...
        });
    return false;
}
function b(){
    //.....
}

我的函数b在ajax调用完成后会执行吗?

完整的解决方案将类似于

function a() {
    var array = [], xhr;
    for (var i = 0; i < 3; i++) {
        xhr = $.post("somePage.php").done(function () {});
        array.push(xhr)
    }
    //create a promise which will be called after all the ajax request are completed
    return $.when.apply($, array);
}

function b() {
    //.....
}

//on succss callback of all the ajax requests created in a call b
a().done(b)

编写一个增量检查,对每个返回的Ajax进行增量检查,如下所示:

increments = 0;
$.post("somePage.php").done(function(){
  // Check if the increments are total to 3
  ++increments;
  if(increments == 3) {
    //do something now such as call b();
  }
  //do stuff here...
});

jQuery ajaxStop方法允许您注册所有Ajax请求完成后要调用的处理程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM