Globally configure all $.ajax requests to support retry on timeout

前端 未结 2 1942
北恋
北恋 2021-01-24 08:17

I need a way to set some kind of timeout function globally with $.ajaxSetup that will allow my Phonegap application to keep retrying an ajax GET or POST every time there is a ti

相关标签:
2条回答
  • 2021-01-24 08:59

    You can use jQuery.ajaxSetup(options).

    Set default values for future Ajax requests. Its use is not recommended.

    Example

    $.ajaxSetup({
      timeout: TimeoutValue
    });
    

    Apart from that if you want perform call again on timeout, I will suggest you to create wrapper for ajax call like.

    function myAjax(options){
        var myOptions = {
            timeout: TimeoutValue,
            error: function( jqXHR, textStatus, errorThrown) {
                //textStatus can one of these "timeout", "error", "abort", and "parsererror"
                if(textStatus === "timeout") {
                    //Recall method once again
                    myAjax(options)
                }
            }           
        };
    
        options = $.extend(true, myOptions , options);
        $.ajax(options)
    }
    

    And Use the function just like $.ajax

    0 讨论(0)
  • 2021-01-24 08:59

    Found a solution to make all AJAX calls work with a retry timeout.

    $(document).ajaxError(function (e, xhr, options) {
        if(xhr.status == 0){
            setTimeout(function(){
                console.log('timeout, retry');
                $.ajax(options);
            }, 5000);
        }
    });
    
    0 讨论(0)
提交回复
热议问题