每个循环中的 Jquery ajax 调用
我在同时使用 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.
}
});
});
干杯。
I'm having a problem when using the jquery .each() and .ajax() functions together. I'm using .each() to loop through 5 elements and am performing the .ajax() call for each one. My problem is that I only want the loop to continue when a response has been received from each ajax request. Currently, all 5 elements are being looped, 5 ajax requests being made, then 5 responses being returned.
Hers's a simple example:
$(".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.
}
});
});
Cheers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
async
选项来使每个请求同步(= 暂停脚本执行,直到每个请求完成):但是,正如文档已经说过的那样,强烈建议不要这样做,因为如果请求挂起或超时,它可能会冻结浏览器。
如果可能的话,最好以可以使用经典回调函数的方式更改代码的架构。
You could use the
async
option for this to make each request synchronous (= halt script execution until each request is finished):but, as the docs already say, this is highly discouraged, as it could freeze the browser if a request hangs or times out.
It would be better to change the architecture of your code in a way that can work with the classical callback functions if at all possible.
佩卡有正确答案。您只需如下编辑脚本即可。
Pekka has the correct answer. You just need to edit your script as below.
我很高兴地说有一种方法...但这有点令人讨厌。
如果您确定请求必须返回一些内容,那么您可以删除“tryIteration”部分。
i'm happy to say there's a way... but it's a bit nasty.
If you are sure the request has to give something back, then you can remove the "tryIteration" part.
您可以使用jquery deferred 和promise 函数来检查异步调用是否成功。 http://joseoncode.com/2011/09/ 26/a-walkthrough-jquery-deferred-and-promise/
You can use the jquery deffered and promise function to check the async call is success or not. http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
虽然已经很晚了,但我为此使用了解决方法
我创建了一个函数来通过传递元素来处理ajax请求
希望它可以帮助任何做类似事情的人
Although it's late, i used a work around for this
I created a function to handle the ajax request by passing the element
Hope it helps anyone doing something similar