我正在向 php 文件发出请求。响应在 .done(function(msg){}) 中处理;和 .fail 这工作正常。但有时请求会出错。我为此重试了一次。重试也有效。但是如果第一次失败并且在 de 2 或 3 中成功,请尝试我的 request.done 不会触发(在 firebug 中我可以看到它是成功的)
我的要求:
var request = $.ajax({
url: "wcf.php",
type: "POST",
dataType: "xml",
async: false,
timeout: 5000,
tryCount: 0,
retryLimit: 3,
data: { barcode: value, curPrxID: currentPrxID, timestamp: (new Date).getTime()},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 500) {
alert('Server error');
}
this.tryCount++;
if (this.tryCount < this.retryLimit) {
$.ajax(this);
//return;
}
}
}) ;
这是 .done 和失败:
request.done(function(msg)
{
$(msg).find("Response").each(function()
{
// my code here
});
});
request.fail(function(jqXHR, textStatus, errorThrown)
{
$("#message").html(errorThrown);
});
最佳答案
.done()
和 .fail()
方法是 Deferred Object 的一部分它在 $.ajax()
返回的 jqXHR
对象中实现。您向它们注册的回调不是 $.ajax()
选项的一部分,因此您无法将它们传递给另一个 $.ajax()
。在您的代码中,您仅订阅父 $.ajax()
延迟对象 回调。为了达到您想要的结果,您应该将整个操作包装在另一个延迟对象中,并使用 .resolveWith()
/.rejectWith()
方法来传递正确的上下文。另外,您还需要记住,延迟对象只能将其状态更改为已解决或拒绝一次(换句话说,如果失败,则不能稍后成功)。所以最终的代码可能如下所示:
var request = $.Deferred(function(deferred) {
$.ajax({
url: 'wcf.php',
type: 'POST',
dataType: 'xml',
async: false,
timeout: 5000,
tryCount: 0,
retryLimit: 3,
data: { barcode: value, curPrxID: currentPrxID, timestamp: (new Date).getTime()},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 500) {
alert('Server error');
}
this.tryCount++;
if (this.tryCount < this.retryLimit) {
$.ajax(this).done(function(data, textStatus, jqXHR) {
deferred.resolveWith(this, [data, textStatus, jqXHR]);
}).fail(function(jqXHR, textStatus, errorThrown) {
if (this.tryCount >= this.retryLimit) {
deferred.rejectWith(this, [jqXHR, textStatus, errorThrown]);
}
});
}
}
}).done(function(data, textStatus, jqXHR) {
deferred.resolveWith(this, [data, textStatus, jqXHR]);
});
}).promise();
request.done(function(msg) {
$(msg).find("Response").each(function() {
//Success code here
});
});
request.fail(function(jqXHR, textStatus, errorThrown) {
$("#message").html(errorThrown);
});
关于javascript - ajax成功后重试没有.done,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17783746/