Make jQuery ajax calls in order

前端 未结 2 775
[愿得一人]
[愿得一人] 2020-12-15 14:39

I want to make a stack of Ajax calls in this way: call(n) starts after call(n-1) finished...

I cannot use async:false for many reasons:

2条回答
  •  独厮守ぢ
    2020-12-15 14:54

    Ok, jQuery Ajax returns a Deferred Object, this can help you achieve this.

    Here is how to do it:

    var args = ['arg1','arg2','arg3','arg4','arg5','arg6'];
    
    deferredPost(0, 5);
    
    function deferredPost(index, max){    
        var delay = Math.random()*3;
        if (index');
            }).then(function(){
                deferredPost(index+1, max);
            });
        } else {
            return $.post('/echo/html/', {html:('Response to '+args[index]), delay:delay}, 
            function(data){
                $('#response').append(data+'
    '); }); } }

    DEMO

    Here I used then function.

    I also recommend to read a little bit more about deferred objects, they can solve a couple of common problems.

提交回复
热议问题