每个循环内的jQuery Ajax调用 [英] Jquery ajax call within an each loop

查看:71
本文介绍了每个循环内的jQuery Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当同时使用jquery .each()和.ajax()函数时,我遇到了问题.我正在使用.each()遍历5个元素,并对每个元素执行.ajax()调用.我的问题是,当每个ajax请求都收到响应时,我只希望循环继续进行.当前,所有5个元素都在循环中,发出5个ajax请求,然后返回5个响应.

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.

一个简单的例子:

$(".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 选项,以使每个请求同步(=停止执行脚本,直到每个请求完成):

You could use the async option for this to make each request synchronous (= halt script execution until each request is finished):

异步 默认情况下,所有请求都是异步发送的(即默认情况下设置为true).如果需要同步请求,请将此选项设置为false.跨域请求和dataType:"jsonp"请求不支持同步操作.请注意,同步请求可能会暂时锁定浏览器,从而在请求处于活动状态时禁用任何操作.

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.

但是,正如文档已经说过的那样,强烈建议不要这样做,因为如果请求挂起或超时,它可能会冻结浏览器.

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.

这篇关于每个循环内的jQuery Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆