且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript, jQuery 同时处理多个 AJAX 请求

更新时间:2022-06-13 23:15:04

使用 jQuery 很容易做到.when();

Ajax 调用可以是任意数量.所以你需要用apply();并创建 ajax 调用数组.现在代码看起来像这样:

Ajax calls can be any number. So you need to use it with apply(); and create array of ajax calls. Now code looks like this:

function makeCall(file, formData) {
    return $.ajax({ // It's necessary to return ajax call 
       url: 'handler.php',
       type: 'POST',
       xhr: function() { // Creating custom XHR to register progress event(If you know better solution - please post ir)
           var xhr = $.ajaxSettings.xhr();

           if (xhr.upload) { // Check if upload property exists
               xhr.upload.addEventListener('progress', progressHandlingFunction.bind(file)); // Registering progress event
           }

           return xhr;
       },
       // Events handlers
       beforeSend: beforeSendHandler.bind(file),
       success: completeHandler,
       data: formData,
       dataType: 'json',
       cache: true,
       contentType: false,
       proccessData: false
    });
}

$('.afu-input').on('change', function() {
    var files = this.files;
    var calls = [];

    $.each(files, function(i, file) {
        uid = generateUniqueId();
        file.id = uid;

        var formData = new formData();

        formData.append(0, file); // Just easier to set index to 0 cause for every file returning new obejct, so is no point to set more indexes

        calls.push(makeCall(file, formData)); // And finally pushing calls to array
    });

    // Using jQuery.when
    // Cause I don't know how many calls will be I'm using "apply" so I can add array instead of one by one calls
    $.when.apply($, calls); // Exactly I don't know why need "$"
}

function beforeSendHandler() {
    console.log(this);
}

function completeHandler(data) {
    console.log(data);
}

function progressHandlingFunction(e) {
    console.log(e);
    console.log(this);
}