Javascript jQuery-完成多个ajax请求
在Javascript jQuery-完成多个ajax请求,javascript,jquery,html,ajax,Javascript,Jquery,Html,Ajax,在$.each()中,我执行一个AJAX请求: $.each(all, function(i,v) { $.ajax({ url: "/mycontroller/"+encodeURIComponent(v), success: function(data){ $('#inner').append(data); } }); }); 现在,
$.each()
中,我执行一个AJAX请求:
$.each(all, function(i,v) {
$.ajax({
url: "/mycontroller/"+encodeURIComponent(v),
success: function(data){
$('#inner').append(data);
}
});
});
现在,如果$中的每个AJAX请求都已完成,我想显示一条消息。但是我如何才能做到这一点,因为AJAX是异步的?您可以利用它。这种方法
提供一种基于零个或多个对象(通常是表示异步事件的延迟对象)执行回调函数的方法
使用简单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")
}
}); });
$.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")
}
}); });