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

后端 未结 5 812
终归单人心
终归单人心 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:13

    I would try jQuery.when so you can still use asynchronous call but deferred, something like :

    jQuery(document).ready(function ($) {
        $.when(
            //for (var i = 0; i < $total_files; i++) {
                $.ajax({
                    // ajax code
                })
            //}
        ).done(function () {
            // perform after ajax loop is done
        }); 
    }); // ready
    

    EDIT : ajax iteration should be done outside $.when and pushed into an array as proposed by charlietfl's answer. You may use an (asynchronous) ajax call and defer it inside $.when though, see JSFIDDLE

提交回复
热议问题