Continue an aborted AJAX (jqXHR) request

2019-03-04 10:09发布

问题:

Is it possible to continue an aborted AJAX (jqXHR) request?

Something like:

$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
  if(/* it enters my conditions */) {
    $.current_request = jQuery.extend(true, {}, jqXHR);
    jqXHR.abort();
  }
}

// some time in the future
$.ajax($.current_request)

This is not working, and I can see one problem that I do not know how to solve: no options are set when sending the request again.

回答1:

Give it a try (not tested)

var request_queue = [], is_processing = false;
$(document).ajaxSend(function(event, jqXHR, ajaxOptions){
    if(/* it enters my conditions */) {
        jqXHR.abort();
        request_queue.push(ajaxOptions);
    }
    else if (request_queue.length && !is_processing) {
        is_processing = true;
        while (ajaxOptions = request_queue.shift())
        {
            $.ajax(ajaxOptions);
        }
        is_processing = false;
    }
});


回答2:

$.ajax(theoptions)

They're currently stored in the ajaxOptions parameter, you'll have to store that somewhere globally to access it later (such as in $.current_request) – Kevin B