Automatically try AJAX request again on Fail

前端 未结 1 1209
后悔当初
后悔当初 2020-12-31 16:48

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

相关标签:
1条回答
  • 2020-12-31 16:53

    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?

    0 讨论(0)
提交回复
热议问题