How to set timeout on $.ajax request and redo it if it takes too long?

前端 未结 4 1120
有刺的猬
有刺的猬 2021-01-20 16:26

Can someone show me a practical example on setting a timeout to my $.ajax request and redo the entire request if the first request is timed out, I\'ve read the docs and didn

4条回答
  •  庸人自扰
    2021-01-20 17:00

    The ajax function takes a timeout parameter and you can check the status in case of error.

    var call =function(){
        $.ajax({
            url: '/ajax/product.php',
            type: 'get',
            timeout: 400,
            ...
            error: function(x, textStatus, m) {
                if (textStatus=="timeout") {
                     call();
                }
            }
        });
    };
    

    You might want to make something a little smarter to avoid permanent calls...

    From the documentation :

    Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

提交回复
热议问题