Jquery ajax call within an each loop

前端 未结 4 1487
日久生厌
日久生厌 2020-12-18 23:03

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

4条回答
  •  清酒与你
    2020-12-19 00:05

    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);
                }
             });
    
        });
    }
    }
    

提交回复
热议问题