【发布时间】:2018-05-01 03:38:32
【问题描述】:
我正在为状态代码 500 定义一个全局 jQuery 错误处理程序(当重试用尽时,带有一些消息的重试机制)。我想覆盖任何可能已添加到$.ajax 请求中的.fail() 承诺。我的代码如下:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function call() {
$.ajax({
url: '/rest/api/v1/some_errorneous_parth',
retryCount:3,
method: 'GET'
}).done(function(data){
console.log(data);
}).fail(function() {
console.log("should not print");
});
}
$(document).ready(function () {
$.ajaxSetup({
retryCount: 3,
error: function retry(response) {
if(response.statuscode === 500) {
if(--this.retryCount){
$.ajax(this);
}
else {
console.log("sorry, i've 'tried everything");
}
}
}
});
});
</script>
</head>
<body>
<input type="button" onclick="call()" value="submit"/>
</body>
</html>
如果服务器返回 500 直到重试计数用完,我希望不打印 should not print。
【问题讨论】:
-
fail()未添加到 ajax 请求中。它正在从 ajax 调用返回的 deferred 中调用 fail 方法。 -
那么我能否以某种方式更改延迟返回的状态,以便不调用失败。
-
承诺/延期只解决/拒绝一次。一旦他们这样做了,据我所知,他们的状态不能被翻转。