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

(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方法以前没有包装过,以避免同一代码重复运行两次。

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

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐