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

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

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

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...