每个循环中的 Jquery ajax 调用

发布于 2024-09-08 22:29:09 字数 573 浏览 8 评论 0原文

我在同时使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

七婞 2024-09-15 22:29:09

您可以使用 async 选项来使每个请求同步(= 暂停脚本执行,直到每个请求完成):

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

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

如果可能的话,最好以可以使用经典回调函数的方式更改代码的架构。

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

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.

稀香 2024-09-15 22:29:09

佩卡有正确答案。您只需如下编辑脚本即可。

$(".element").each(function() {
    var id= $(this).find(('txtId').val();
    $.ajax({
       type: "POST",
       async: false,
       url: "/Handlers/Handler.ashx",
       data: "ID=" + id,
       success: function(xml){

       }
     });

});

Pekka has the correct answer. You just need to edit your script as below.

$(".element").each(function() {
    var id= $(this).find(('txtId').val();
    $.ajax({
       type: "POST",
       async: false,
       url: "/Handlers/Handler.ashx",
       data: "ID=" + id,
       success: function(xml){

       }
     });

});
微暖i 2024-09-15 22:29:09

我很高兴地说有一种方法...但这有点令人讨厌。

如果您确定请求必须返回一些内容,那么您可以删除“tryIteration”部分。

$(document).ready(function() {

        loop(".buttonsPromotion", 0);

});

function loop(elements, tryIteration) {
//HOW MANY TRIES UNTIL WE STOP CHECKING
if(tryIteration<7){

    $(elements).each(function() {            
        var actuel = $(this);
        $.ajax({
           url: "write your link here",
           data: {},
           dataType: 'json',
           async: true,
           success: function(data){
               //HERE WE KNOW THE AJAX REQUEST WENT OK
               actuel.addClass('AjaxOK');    
           },
           error:function(thrownError){
                console.log(thrownError);
                //WE MAKE ANOTHER EACH ON ALL ELEMENT THAT WENT BAD
                var elemToRetry = actuel.not('AjaxOK');
                loop(elemToRetry, ++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.

$(document).ready(function() {

        loop(".buttonsPromotion", 0);

});

function loop(elements, tryIteration) {
//HOW MANY TRIES UNTIL WE STOP CHECKING
if(tryIteration<7){

    $(elements).each(function() {            
        var actuel = $(this);
        $.ajax({
           url: "write your link here",
           data: {},
           dataType: 'json',
           async: true,
           success: function(data){
               //HERE WE KNOW THE AJAX REQUEST WENT OK
               actuel.addClass('AjaxOK');    
           },
           error:function(thrownError){
                console.log(thrownError);
                //WE MAKE ANOTHER EACH ON ALL ELEMENT THAT WENT BAD
                var elemToRetry = actuel.not('AjaxOK');
                loop(elemToRetry, ++tryIteration);
            }
         });

    });
}
}
余生再见 2024-09-15 22:29:09

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

傲鸠 2024-09-15 22:29:09

虽然已经很晚了,但我为此使用了解决方法
我创建了一个函数来通过传递元素来处理ajax请求

function ajax_request(element){
    var id = element.find('.txtId').val();
    console.log(id);
    $.ajax({
        type: "POST",
        url: "/Handlers/Handler.ashx",
        data: "ID=" + id,
        success: function(xml){
            console.log(xml);
        }
     });
}

$(".element").each(function() {
    // run the ajax function for current element
    ajax_request($(this));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element">
    <input class="txtId" value="textid1"/>
</div>
<div class="element">
    <input class="txtId" value="textid2"/>
</div>
<div class="element">
    <input class="txtId" value="textid3"/>
</div>

希望它可以帮助任何做类似事情的人

Although it's late, i used a work around for this
I created a function to handle the ajax request by passing the element

function ajax_request(element){
    var id = element.find('.txtId').val();
    console.log(id);
    $.ajax({
        type: "POST",
        url: "/Handlers/Handler.ashx",
        data: "ID=" + id,
        success: function(xml){
            console.log(xml);
        }
     });
}

$(".element").each(function() {
    // run the ajax function for current element
    ajax_request($(this));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element">
    <input class="txtId" value="textid1"/>
</div>
<div class="element">
    <input class="txtId" value="textid2"/>
</div>
<div class="element">
    <input class="txtId" value="textid3"/>
</div>

Hope it helps anyone doing something similar

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文