How to wait until jQuery ajax request finishes in a loop?

后端 未结 5 811
终归单人心
终归单人心 2020-11-27 02:42

I have that code :

for (var i = 0; i < $total_files; i++) {
  $.ajax({
    type: \'POST\',
    url: \'uploading.php\',
    context: $(this),
    dataType:         


        
5条回答
  •  执笔经年
    2020-11-27 03:31

    Populate an array with each call and call the next item when the previous is done.

    You could try something like that:

        window.syncUpload = {
    
            queue : [],
    
            upload : function(imagesCount) {
    
                var $total_files = imagesCount, data_string = "";
    
                /* Populates queue array with all ajax calls you are going to need */
                for (var i=0; i < $total_files; i++) {       
                    this.queue.push({
                        type: 'POST',
                        url: 'uploading.php',
                        context: $(this),
                        dataType: 'json',
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: data_string,
                        success: function(datas) {
                        //does something
                        },
                        error: function(e){
                            alert('error, try again');
                        },
                        /* When the ajax finished it'll fire the complete event, so we
                           call the next image to be uploaded.
                        */
                        complete : function() {
                            this[0].uploadNext();
                        }
                    });
                }
    
                this.uploadNext();
            },
    
            uploadNext : function() {
                var queue = this.queue;
    
                /* If there's something left in the array, send it */
                if (queue.length > 0) {
                    /* Create ajax call and remove item from array */
                    $.ajax(queue.shift(0));
                }
    
    
            }
    
        }
    

    Just call it using syncUpload.upload(NUMBER_OF_IMAGES);

提交回复
热议问题