如何采取行动时,所有的Ajax在每个循环的成功调用?有的、行动、在每个、Ajax

2023-09-10 16:05:39 作者:关掉月亮啦

我打电话。每次循环中阿贾克斯jQuery的功能,我想在做一个动作刚才的所有Ajax调用循环完成和成功里面。

I call ajax jquery function inside .each loop, and I want to do an action just when all the ajax calls inside the loop finish and success.

$(".checked-box").each(function () {
     // ajax call goes here
});
$('.messsage').html('all requests done');

如何做到这一点?没有异步:假,因为这阻止浏览器

How to do that? without async: false because this blocks the browser.

推荐答案

这是一个方法:

var numberOfPendingRequests = 8;
$(".checked-box").each(function () {   
   $.ajax({
     success: function(){
        ...
        numberOfPendingRequests --;
        if(numberOfPendingRequests == 0) allDone();
     }
   });
});
function allDone(){
  $('.messsage').html('all requests done');
}

您可以计算初始 numberOfPendingRequests 根据您的复选框的数量或0每个Ajax请求之前的增量就启动它,但这是一般的想法。

You can calculate the initial numberOfPendingRequests based on your number of checkboxes or start it at 0 an increment it before each ajax request, but this is the general idea.

希望这有助于。干杯