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

伪代码:


$(document).ajaxError(function(e, xhr, options, error) {

  xhr.retry()

})

更好的是某种指数补偿


DIEA
浏览 1352回答 3
3回答

慕仙森

像这样:$.ajax({&nbsp; &nbsp; url : 'someurl',&nbsp; &nbsp; type : 'POST',&nbsp; &nbsp; data :&nbsp; ....,&nbsp; &nbsp;&nbsp; &nbsp; tryCount : 0,&nbsp; &nbsp; retryLimit : 3,&nbsp; &nbsp; success : function(json) {&nbsp; &nbsp; &nbsp; &nbsp; //do something&nbsp; &nbsp; },&nbsp; &nbsp; error : function(xhr, textStatus, errorThrown ) {&nbsp; &nbsp; &nbsp; &nbsp; if (textStatus == 'timeout') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.tryCount++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (this.tryCount <= this.retryLimit) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //try again&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $.ajax(this);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (xhr.status == 500) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //handle error&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //handle error&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP