【问题标题】:retry jquery ajax on failure失败时重试jquery ajax
【发布时间】:2013-11-14 04:07:00
【问题描述】:

我有一个 jquery-ajax 调用控制器中的一个动作。有时通话失败,所以我想重试一次。

jQuery-ajax:

return ajax({
    url: getRootDir() + urlDoTask, // urlDoTask is something like "/Action/"
    data: { param: someParam },
    type: 'POST',
    dataType: 'json',
    tryCount: 0,
    retryLimit: 3
}).then(function (data) {
    // Do some stuff
    return ....
}, function (xhr, textStatus, errorThrown) {

    if (textStatus == 'timeout' || (xhr.responseText == "" && textStatus == 'error')) {
        this.tryCount++; // this is always 1
        if (this.tryCount <= this.retryLimit) {
            //try again
            $.ajax(this);
            return;
        }
        return; // this point is never reached
    }
    if (xhr.status == 404) {
        // Do some stuff
    }

    return ... // I want to reach it after this.tryCount > this.retryLimit
});

function getRootDir() {
    var loc = window.location.pathname;
    var dir = loc.substring(0, loc.lastIndexOf('/'));

    return dir;
}

上面的代码不起作用,每次ajax调用失败时tryCount总是1。此外,一旦 this.tryCount 大于 this.retryLimit,就永远不会到达最后的返回值。

想法?

【问题讨论】:

标签: javascript jquery


【解决方案1】:

我看到的东西很少。传入的参数实际上并不是对象的成员。它只是一个密钥/对的 JSON 映射。所以函数中不会存在“this.tryCount”之类的东西。您可以做的是在您的函数(或调试)中放置警报并查看值是什么。可能它们是未定义的或 0。

【讨论】:

  • 感谢您的评论,但您能否告诉我如何在失败时重试相同的 ajax 调用,即一旦失败,在控制器中调用相同的操作。一个例子将不胜感激。
猜你喜欢
  • 2014-05-14
  • 1970-01-01
  • 1970-01-01
  • 2015-07-25
  • 2013-12-25
  • 2015-11-05
  • 1970-01-01
  • 2012-04-14
  • 2019-01-14
相关资源
最近更新 更多