简体   繁体   English

重试ajax调用直到成功

[英]Retry ajax call until successful

I have an Ajax call that I would like to retry when failing, based on this current code : 根据当前代码,我有一个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");

        }
    });

I have tried to encapsulate it inside a new function with a callback to this function in error (together with setTimeout ) but it never starts ... 我试图将它封装在一个新函数中, error回调此函数(与setTimeout一起),但它永远不会启动...

Also There could be concurrent Ajax calls such as this one for different dom elements. 此外,对于不同的dom元素,可能会有并发Ajax调用。

(there is this useful thread but I am so bad in JS I cannot adapt it to my code How to repeat ajax call until success ) (有这个有用的线程,但我在JS中这么糟糕我不能适应我的代码如何重复ajax调用直到成功

That link you posted contains the exact answer ... you just need to wrap your code in a function so it can be used recursively: 您发布的链接包含确切的答案...您只需将代码包装在函数中,以便可以递归使用它:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM