全局配置所有$.ajax请求以支持超时重试

Globally configure all $.ajax requests to support retry on timeout

本文关键字:支持 超时 重试 请求 ajax 配置 全局      更新时间:2023-09-26

我需要一种方法来使用$.ajaxSetup全局设置某种超时功能,这将允许我的Phonegap应用程序在每次由于互联网连接不好而超时时都不断重试ajax GET或POST。

我使用Backbone.js,所以大多数jquery插件都不适用于此,我会帮助编写一段全局代码来处理重试。

谢谢。

您可以使用jQuery.ajaxSetup(选项).

为将来的Ajax请求设置默认值。不建议使用它。

示例

$.ajaxSetup({
  timeout: TimeoutValue
});

除此之外,如果您想在超时时再次执行调用,我建议您创建类似ajax调用的包装器。

function myAjax(options){
    var myOptions = {
        timeout: TimeoutValue,
        error: function( jqXHR, textStatus, errorThrown) {
            //textStatus can one of these "timeout", "error", "abort", and "parsererror"
            if(textStatus === "timeout") {
                //Recall method once again
                myAjax(options)
            }
        }           
    };
    options = $.extend(true, myOptions , options);
    $.ajax(options)
}

使用与$.ajax 类似的函数

找到了一个解决方案,使所有AJAX调用都能在重试超时的情况下工作。

$(document).ajaxError(function (e, xhr, options) {
    if(xhr.status == 0){
        setTimeout(function(){
            console.log('timeout, retry');
            $.ajax(options);
        }, 5000);
    }
});