拉丁的传说
一种方法是使用包装函数:(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 settingsvar ajaxSettings = { type : 'GET', url : '', dataType : 'json', contentType : 'application/json', retries : 3 // 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, // { console.log('failed') });需要考虑的一点是,要确保该$.ajax方法以前没有包装过,以避免同一代码重复运行两次。您可以将这些摘要(按原样)复制粘贴到控制台以对其进行测试