Jquery 'each' 等待 ajax 进程完成,然后继续循环



我想在选中的复选框的每个循环中运行ajax。然而,"jquery each"忽略了ajax进程。完成或未完成的循环将继续。对不起,我的语言不好,希望你能理解。

下面是我编写的代码示例:

$('input[name="options[]"]:checked').each(function() {
jQuery.ajax({
url: "www.example.com",
type: "POST",
data: {
name:name
},
success: function(data) {
// do something
}
});
});

我尝试在ajax选项中使用async:false,但页面冻结,并将在过程完成后恢复正常。

对于任何类型的Promise batch你所要做的就是将它们集合到数组中然后传递给&;batch promises &;函数。不管是jQuery, Angular还是其他的


// Gather all promises returned from $.ajax
var allPromises = [];
$('input[name="options[]"]:checked').each(function () {
allPromises.push(
callAjax($(this).val()
);
});
$.when(allPromises).then(function () {/* do something after all*/})
function callAjax(name) {
// Returns promise from $.ajax
return jQuery.ajax({
url: "www.example.com",
type: "POST",
data: {name: name},
success: function (data) {/* do something after this call*/}
});
}

这是使用fetch()的另一种解决方案,因为它在所有现代浏览器中都可用(不需要jQuery):

const jsrv='https://jsonplaceholder.typicode.com/',
arr='users,posts,comments'.split(',');

Promise.all(arr.map(e=>fetch(jsrv+e).then(r=>r.json())))
.then(console.log)
.as-console-wrapper {max-height:100% !important}

在这个示例脚本中,我收集了对typicode.com提供的公共可用资源的三个Ajax调用的响应:结果数组由三个数组组成,其中包含用户、帖子和评论。在我的演示中,我只提供console.log作为处理函数。这在现实生活中当然是不同的。

fetch也可以与POST一起使用,详细信息请参见此处:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch。

相关内容

最新更新