同时使用 jquery .each() 和 .ajax() 函数时遇到问题。我使用 .each() 循环 5 个元素,并对每个元素执行 .ajax() 调用。我的问题是我只希望循环在收到每个 ajax 请求的响应时继续。目前,所有 5 个元素都在循环,发出 5 个 ajax 请求,然后返回 5 个响应。
她是一个简单的例子:
$(".element").each(function() {
var id= $(this).find(('txtId').val();
$.ajax({
type: "POST",
url: "/Handlers/Handler.ashx",
data: "ID=" + id,
success: function(xml){
// I would like the each() loop to pause until this is hit,
// and some additional logic can be performed.
}
});
});
干杯。
最佳答案
您可以使用async
使每个请求同步的选项(= 暂停脚本执行,直到每个请求完成):
async By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
但是,正如文档已经说过的那样,强烈建议不要这样做,因为如果请求挂起或超时,它可能会卡住浏览器。
如果可能的话,最好以可以使用经典回调函数的方式更改代码架构。
关于每个循环中的 Jquery ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3237553/