在$.each()中,我执行AJAX请求:
$.each(all, function(i,v) {
$.ajax({
url: "/mycontroller/"+encodeURIComponent(v),
success: function(data){
$('#inner').append(data);
}
});
});现在,如果$.each()中的每个AJAX请求都完成了,我想显示一条消息。但是我如何做到这一点,因为AJAX是异步的?
发布于 2016-09-20 08:38:30
使用简单的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");
}
}
});
});发布于 2016-09-20 08:29:02
您可以利用jQuery.when()。这种方法
提供一种基于零或多个对象(通常是表示异步事件的延迟对象)执行回调函数的方法。
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
});发布于 2016-09-28 07:28:52
使用异步: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")
}
}); });https://stackoverflow.com/questions/39589148
复制相似问题