1

我使用 ajax 发出一个 GET 请求,并期望返回一个 JSON 值。

但是,我的主机安装了防火墙。它每秒只需要 2 个请求,否则会阻塞连接并显示错误页面。(空白页。)因此,如果我在第二个请求中发出 3 个请求,则第三个请求永远不会检索 JSON 响应。因此,loading.gif 不断转动。

如何在 jQuery 中设置超时,比如说 5 秒,所以它会回调超时函数?

4

2 回答 2

1

尝试这个:

$.ajax({
    url: YourUrl,
    async: true,
    timeout: 5000,       //5 seconds
    success: function(args) { 

                     // on success code
    }
})
于 2013-02-26T02:25:35.113 回答
0

您可以使用超时函数作为参数创建自定义 GET 请求:

$.getWithTimeOut = function(url, params, datatype, onsuccessfunction, aftertimeoutfunction, timeout){
     $.get(url, params, function(data) {
          onsuccessfunction(data);
          setTimeout(aftertimeoutfunction, timeout);
     }, datatype);
};

然后你只需调用:

$.getWithTimeOut('url/url', { param1: value1 }, 'json', function(data){
     //success code here
}, function(/*params*/){
   //timeout code here
}, 5000);
于 2013-02-26T02:46:34.353 回答