Javascript - AJAX request inside loops

前端 未结 3 1739
日久生厌
日久生厌 2020-12-05 11:55

I\'m using jQuery to send an AJAX request, retrieving data from a server.

That data is then appended to an element. This should happen 5 times, but it will always ha

3条回答
  •  囚心锁ツ
    2020-12-05 12:28

    Very interesting methods provided by jQuery when you are executing loops of asyncroniouse request and detect all ajax request completed or not. It is possible by using

    var users=["a","b","c","d","e","f","g","h"];
    
    var async_request=[];
    var responses=[];
    for(i in users)
    {
        // you can push  any aysnc method handler
        async_request.push($.ajax({
            url:'', // your url
            method:'post', // method GET or POST
            data:{user_name: users[i]},
            success: function(data){
                console.log('success of ajax response')
                responses.push(data);
            }
        }));
    }
    
    
    $.when.apply(null, async_request).done( function(){
        // all done
        console.log('all request completed')
        console.log(responses);
    });
    

    Here $.when provides a way to execute callback functions based on zero or more objects, usually Deferred objects that represent asynchronous events.

    apply() converts array elements as different arguments in function

    $.done is call function after all async. request are completed.

提交回复
热议问题