微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在每个循环中调用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. 

       }
     });

});

干杯.

解决方法

您可以使用 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.

但是,正如文档已经说过的那样,这是非常气馁的,因为如果请求挂起或超时,它可能会冻结浏览器.

如果可能的话,最好以一种可以使用经典回调函数的方式更改代码的体系结构.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐