Javascript 重复jqueryajax请求

Javascript 重复jqueryajax请求,javascript,jquery,Javascript,Jquery,我向服务器发出ajax请求。有时我会收到502错误。所以,如果发生这种情况,就会调用error()方法 如果收到错误,如何重复请求?代码应如下所示: $.ajax({ url: 'http://server/test.php', type: 'GET', dataType: 'jsonp', cache: 'false', timeout

我向服务器发出ajax请求。有时我会收到502错误。所以,如果发生这种情况,就会调用error()方法

如果收到错误,如何重复请求?代码应如下所示:

$.ajax({
                url: 'http://server/test.php',
                type: 'GET',
                dataType: 'jsonp',
                cache: 'false',
                timeout: 32000,
                success: function(data) {
                  //some actions here
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log("Error[refresh]: " + textStatus);
                    console.log(jqXHR);
                    // here I want to repeat the request like "this.repeat()"
                },
            });

将代码放入函数中,然后再次调用此函数。比如:

function ajaxFunction()
{
 ....
error:function(){ajaxFunction();}
}

你可以这样做

function ajaxCall(){
      $.ajax({
                url: 'http://server/test.php',
                type: 'GET',
                dataType: 'jsonp',
                cache: 'false',
                timeout: 32000,
                success: function(data) {
                  //some actions here
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log("Error[refresh]: " + textStatus);
                    console.log(jqXHR);
                    ajaxCall(); // recursion call to method.
                },
            });
}

根据哈达斯的建议,具有调用限制:

function ajaxCall(count) {
    count = typeof count == 'undefined' ? 0 : count;
    limit = 5;
    if(count === limit) return;
    // no need to specify cache and type:
    //   type has 'GET' as default value
    //   cache has default value of false if the dataType is jsonp
    $.ajax({        
        url: 'http://server/test.php',
        dataType: 'jsonp', 
        timeout: 32000,
        async: false 
    }).done(function(data) {
        // some actions here
    }).fail(function(jqXHR, textStatus, errorThrown) {
        count += 1;
        console.log("Error[refresh]: " + textStatus);
        console.log(jqXHR);
        // 500, 1000, 1500, 2000 etc
        setTimeout(function() {
            ajaxCall(count);
        }, 500*count);
    });
};

从我对递归的了解来看,什么可以阻止函数自身重复——例如,基本情况是什么?可能不是真正的评论,但我想我会问…@Rob-如果你想避免永远调用,你可以计算调用次数,并在几次之后停止。这很有意义-因此有一个初始值为0的变量,在每次调用后递增1,并将调用放入while循环中(将一直运行,直到递增的值达到特定值)。这里的count将是一个全局变量。如果是,我们是否更改第2行