重试ajax调用直到成功

时间:2017-12-12 23:28:43

标签: javascript

根据当前代码,我有一个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中很糟糕,我无法将其改编为我的代码How to repeat ajax call until success

2 个答案:

答案 0 :(得分:5)

您发布的链接包含确切的答案...您只需要将代码包装在一个函数中,以便可以递归使用它:

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()

答案 1 :(得分:0)

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>";
})
相关问题