超时后重试ajax请求

时间:2014-04-25 08:15:33

标签: javascript jquery ajax

我使用预过滤器重做最多2次ajax请求,请参阅下面的代码。

但问题是,也调用了ajax请求的原始fail()处理程序。当然,这需要禁用。

    $.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    // retry not set or less than 2 : retry not requested
    if (!originalOptions.retryMax || !originalOptions.retryMax >= 2) {
        return;
    }
    // no timeout was setup
    if (!originalOptions.timeout > 0) {
        return;
    }

    if (originalOptions.retryCount) {
        originalOptions.retryCount++;
    } else {
        originalOptions.retryCount = 1;
        // save the original error callback for later
        if (originalOptions.error) {
            originalOptions._error = originalOptions.error;
        }
    };

    // overwrite *current request* error callback
    options.error = $.noop();

    // setup our own deferred object to also support promises that are only invoked
    // once all of the retry attempts have been exhausted
    var dfd = $.Deferred();

    jqXHR.done(dfd.resolve);

    // if the request fails, do something else yet still resolve
    jqXHR.fail(function() {
        var args = Array.prototype.slice.call(arguments);

        if (originalOptions.retryCount >= originalOptions.retryMax || jqXHR.statusText !== "timeout") {
            // add our _error callback to our promise object
            if (originalOptions._error) {
                dfd.fail(originalOptions._error);
            }
            dfd.rejectWith(jqXHR, args);
        } else {
            $.ajax(originalOptions).then(dfd.resolve, dfd.reject);
        }
    });
});

我的要求是:我收到console.log消息"我们失败了#34;在第一次重做请求的同时。知道如何解决这个问题吗?

        $.ajax({
        url: url,
        crossDomain: true,
        dataType: "json",
        type: type,
        timeout: 20000,
        async: (async === undefined ? true : async),
        beforeSend: beforeSend,
        retryMax: (type == "POST" ? 0 : 2),
        data: data
    }).done(function(response, status, xhr) {
            }).fail(function(xhr, textStatus, error) {
        console.log("WE ARE IN FAIL");
    });

1 个答案:

答案 0 :(得分:0)

更简单的方法(抱歉,我只有时间编写部分代码):(

创建一个递归函数来处理ajax请求并获取参数+一个计数器。

var MyFuncAjax = function(params, counter){
  if(counter <= 0){ return true; }

  $ajax({
    ...
    timeout: params.timeout
    ...
  })
  ...fail(function(xhr...){
    MyFuncAjax(params, --counter)
  })
}

然后叫它

MyFuncAjax({timeout: 20000, ....}, 2)

瞧瞧:)