[英]Retry ajax call until successful
根据当前代码,我有一个Ajax调用,我想在失败时重试:
$.ajax({
url: "<%= my_ruby_on_rails_controller_url_here %>",
datatype: "json",
type: "GET",
success: function (json) {
document.getElementById("factureload" + json.hashed_id).innerHTML = "<a href='" + json.address + "'><img class='pdficonstyling' src='/assets/pdf4.svg' alt='pdf icon' /> facture_" + json.numfacture + "</a>";
},
error: function () {
alert("fail");
}
});
我试图将它封装在一个新函数中, error
回调此函数(与setTimeout
一起),但它永远不会启动...
此外,对于不同的dom元素,可能会有并发Ajax调用。
(有这个有用的线程,但我在JS中这么糟糕我不能适应我的代码如何重复ajax调用直到成功 )
您发布的链接包含确切的答案...您只需将代码包装在函数中,以便可以递归使用它:
function myAjaxRequest () {
$.ajax({
url: "<%= my_ruby_on_rails_controller_url_here %>",
datatype: "json",
type: "GET",
success: function (json) {
document.getElementById("factureload" + json.hashed_id).innerHTML = "<a href='" + json.address + "'><img class='pdficonstyling' src='/assets/pdf4.svg' alt='pdf icon' /> facture_" + json.numfacture + "</a>";
},
error: function () {
setTimeout(() => {
myAjaxRequest()
}, 5000) // if there was an error, wait 5 seconds and re-run the function
}
})
}
myAjaxRequest()
function tryUntilSuccess(success) {
$.ajax({
url: '<%= my_ruby_on_rails_controller_url_here %>',
datatype: 'json',
type: 'GET',
success: success,
error: function(err) {
console.log('Request failed. Retrying...', err)
tryUntilSuccess(success)
},
})
}
tryUntilSuccess(function onSuccess(json) {
document.getElementById("factureload" + json.hashed_id).innerHTML = "<a href='" + json.address + "'><img class='pdficonstyling' src='/assets/pdf4.svg' alt='pdf icon' /> facture_" + json.numfacture + "</a>";
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.