jQuery -完成多个ajax请求

jQuery - completion of multiple ajax-requests

本文关键字:ajax 请求 jQuery      更新时间:2023-09-26

$.each()中我做了一个ajax请求:

$.each(all, function(i,v) {                                 
    $.ajax({
        url: "/mycontroller/"+encodeURIComponent(v),
        success: function(data){ 
            $('#inner').append(data);
        }
    }); 
});

现在我想显示一条消息,如果$.each()中的每个ajax请求都完成了。但是我该怎么做呢,因为AJAX是异步的?

您可以使用jQuery.when()。这个方法

提供了一种基于零个或多个对象执行回调函数的方法,通常是表示异步事件的Deferred对象。

var ajaxRequests = all.map(function(x) { 
    return $.ajax({
        url: "/mycontroller/"+encodeURIComponent(x),
        success: function(data){ 
            $('#inner').append(data);
    }
}); 
jQuery.when.apply(this, ajaxRequests).then(function() {
    // do what you want
});

用简单的javascript你可以这样做:

var counter = 0;
$.each(all, function(i,v) {                                 
    $.ajax({
        url: "/mycontroller/"+encodeURIComponent(v),
        success: function(data){ 
            $('#inner').append(data);
            counter++; //increment the counter
        },
        error: function(){
            counter++; //increment the counter
        },
        complete : function(){
            //check whether all requests been processed or not
            if(counter == all.length)
            {
                alert("All request processed");
            }
        }
    }); 
});

使用async:false使ajax请求在浏览器传递给其他代码之前完成

$.each(all, function(i,v) {                                 
   $.ajax({
       type: 'POST',
       url: "/mycontroller/"+encodeURIComponent(v),
       data: row,    
       success: function(data){ 
          $('#inner').append(data);
         }
       error: function() {
       console.log("Error")
    }
  });   });