0

我想在所选复选框的每个循环中运行 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,但页面冻结,并在该过程完成后恢复正常。

4

2 回答 2

1

因此,对于任何类型的 Promise 批次,您所要做的就是将它们全部收集到数组中并传递给“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*/}
    });
}

于 2021-10-18T18:56:39.593 回答
0

这是使用的替代解决方案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 。

于 2021-10-18T19:15:14.517 回答