再次自动尝试失败AJAX请求 [英] Automatically try AJAX request again on Fail

查看:536
本文介绍了再次自动尝试失败AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了,你可以指定一个Ajax请求失败怎么一般做,是有可能有它在某种循环的再次尝试,以便它会尝试的时候,至少停止前X量?我以前都用这个code:

I have seen that you can specify what to do generally if an ajax request fails, is it possible to have it try again in some sort of a loop so that it tries at least x amount of times before it stops? I have used this code before:

$.ajaxSetup({
  "error":function() {   
    alert("error");
}});

将适用于所有的AJAX请求(纠正我,如果我错了)。

Which will apply to all AJAX requests (correct me if I'm wrong).

我想做的事情是这样的:

I want to do something like this:

$.ajaxSetup({
  "error":function() {   
    $(this).ajax;
}});

将这项工作?甚至更好:这会不会以正确的方式做到这一点?我想包重试的计数系统,使之不会无限地重试。在我的应用程序9次了10年它会正常工作,但我用的接口将返回一个错误。这些API的每一个现在,然后一个

Would this work? Or even better: would this be the right way to do it? I would wrap the retry in a count system so that it doesn't infinitely retry. In my application 9 times out of 10 it will work correctly but every now and then one of the APIs I'm interfacing with will return an error.

任何建议,帮助,谢谢!

Any suggestions would help, thanks!

推荐答案

您可以尝试这样的事:     

You can try something like this:

    var attempts;
    function doAjaxRequest() {
        attempts = 0;
        doAjaxRequestLoop();
    }

    function doAjaxRequestLoop() {
        attempts += 1;
        if (attempts > 10) {
            alert('too many attempts.');
            return;
        }

        $.ajax({ // do your request
            error: function (error) {
                doAjaxRequestLoop();
            }
        });
    }

</script>

虽然我可能会建议反对。如果请求失败,你可能想找出失败的原因。如果用户丢失了他们的互联网连接?任何进一步的尝试很可能会再次失败,为什么重试?

Although I might recommend against it. If the request fails you may want to find out why it failed. What if the user lost their internet connect? Any further attempts are likely to fail again so why retry?

这篇关于再次自动尝试失败AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆