ajax 自动重试,使用jQuery在失败时重试AJAX请求的最佳方法是什么?

一种方法是使用包装函数:

(function runAjax(retries, delay){

delay = delay || 1000;

$.ajax({

type        : 'GET',

url         : '',

dataType    : 'json',

contentType : 'application/json'

})

.fail(function(){

console.log(retries); // prrint retry count

retries > 0 && setTimeout(function(){

runAjax(--retries);

},delay);

})

})(3, 100);

另一种方法是retries在$.ajax

// define ajax settings

var ajaxSettings = {

type        : 'GET',

url         : '',

dataType    : 'json',

contentType : 'application/json',

retries     : 3  //                 

};

// run initial ajax

$.ajax(ajaxSettings).fail(onFail)

// on fail, retry by creating a new Ajax deferred

function onFail(){

if( ajaxSettings.retries-- > 0 )

setTimeout(function(){

$.ajax(ajaxSettings).fail(onFail);

}, 1000);

}

另一种方法(GIST)-覆盖原始$.ajax格式(对DRY更好)

// enhance the original "$.ajax" with a retry mechanism

$.ajax = (($oldAjax) => {

// on fail, retry by creating a new Ajax deferred

function check(a,b,c){

var shouldRetry = b != 'success' && b != 'parsererror';

if( shouldRetry && --this.retries > 0 )

setTimeout(() => { $.ajax(this) }, this.retryInterval || 100);

}

return settings => $oldAjax(settings).always(check)

})($.ajax);

// now we can use the "retries" property if we need to retry on fail

$.ajax({

type          : 'GET',

url           : 'http://www.whatever123.gov',

timeout       : 2000,

retries       : 3,     //       

retryInterval : 2000   //       

})

// Problem: "fail" will only be called once, and not for each retry

.fail(()=>{

console.log('failed')

});

需要考虑的一点是,要确保该$.ajax方法以前没有包装过,以避免同一代码重复运行两次。

您可以将这些摘要(按原样)复制粘贴到控制台以对其进行测试

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值