伪代码:
$(document).ajaxError(function(e, xhr, options, error) {
xhr.retry()
})
更好的办法是某种指数退让。
发布于 2012-04-05 15:44:23
如下所示:
$.ajax({
url : 'someurl',
type : 'POST',
data : ....,
tryCount : 0,
retryLimit : 3,
success : function(json) {
//do something
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
//handle error
} else {
//handle error
}
}
});
发布于 2012-08-25 17:37:25
我已经在下面的代码中获得了很多成功(示例:http://jsfiddle.net/uZSFK/)
$.ajaxSetup({
timeout: 3000,
retryAfter:7000
});
function func( param ){
$.ajax( 'http://www.example.com/' )
.success( function() {
console.log( 'Ajax request worked' );
})
.error(function() {
console.log( 'Ajax request failed...' );
setTimeout ( function(){ func( param ) }, $.ajaxSetup().retryAfter );
});
}
发布于 2018-06-21 01:15:23
如果有人在ajax调用之后调用.done()
,这些答案都不起作用,因为您没有成功的方法来附加到未来的回调。所以如果有人这么做了:
$.ajax({...someoptions...}).done(mySuccessFunc);
那么mySuccessFunc
将不会在重试时被调用。这是我的解决方案,大量借用@cjpak的answer here。在我的案例中,我希望在AWS的API Gateway响应502错误时重试。
const RETRY_WAIT = [10 * 1000, 5 * 1000, 2 * 1000];
// This is what tells JQuery to retry $.ajax requests
// Ideas for this borrowed from https://stackoverflow.com/a/12446363/491553
$.ajaxPrefilter(function(opts, originalOpts, jqXHR) {
if(opts.retryCount === undefined) {
opts.retryCount = 3;
}
// Our own deferred object to handle done/fail callbacks
let dfd = $.Deferred();
// If the request works, return normally
jqXHR.done(dfd.resolve);
// If the request fails, retry a few times, yet still resolve
jqXHR.fail((xhr, textStatus, errorThrown) => {
console.log("Caught error: " + JSON.stringify(xhr) + ", textStatus: " + textStatus + ", errorThrown: " + errorThrown);
if (xhr && xhr.readyState === 0 && xhr.status === 0 && xhr.statusText === "error") {
// API Gateway gave up. Let's retry.
if (opts.retryCount-- > 0) {
let retryWait = RETRY_WAIT[opts.retryCount];
console.log("Retrying after waiting " + retryWait + " ms...");
setTimeout(() => {
// Retry with a copied originalOpts with retryCount.
let newOpts = $.extend({}, originalOpts, {
retryCount: opts.retryCount
});
$.ajax(newOpts).done(dfd.resolve);
}, retryWait);
} else {
alert("Cannot reach the server. Please check your internet connection and then try again.");
}
} else {
defaultFailFunction(xhr, textStatus, errorThrown); // or you could call dfd.reject if your users call $.ajax().fail()
}
});
// NOW override the jqXHR's promise functions with our deferred
return dfd.promise(jqXHR);
});
这段代码将后退并在2秒后重试,然后是5秒,然后是10秒,您可以通过修改RETRY_WAIT常量对其进行编辑。
AWS支持建议我们添加一次重试,因为它对我们来说只有一次蓝月亮。
https://stackoverflow.com/questions/10024469
复制相似问题