jQuery getJSON 超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4138470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:44:31  来源:igfitidea点击:

jQuery getJSON with timeout

jquerytimeoutgetjson

提问by Scott B

When making a call out to the yahoo web service (http://boss.yahooapis.com/ysearch) to return a data set, is it possible to set a timeout and exit the routine once its elapsed?

当调用雅虎 Web 服务 (http://boss.yahooapis.com/ysearch) 以返回数据集时,是否可以设置超时并在超时后退出例程?

jQuery.getJSON("http://boss.yahooapis.com/ysearch/...etc",
        function (data) {
              //result set here
            });

回答by Galen

You can use the timeout option

您可以使用超时选项

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback,
  timeout: 3000 //3 second timeout
});

回答by anson chow

 $.ajax({ 
  url: url, 
  dataType: 'json', 
  data: data, 
  success: callback, 
  timeout: 3000 //3 second timeout, 
  error: function(jqXHR, status, errorThrown){   //the status returned will be "timeout" 
     //do something 
  } 
}); 

回答by Mahesh

    function testAjax() {
        var params = "test=123";
        var isneedtoKillAjax = true; // set this true

        // Fire the checkajaxkill method after 10 seonds
        setTimeout(function() {
            checkajaxkill();
        }, 10000); // 10 seconds                

        // For testing purpose set the sleep for 12 seconds in php page 

        var myAjaxCall = jQuery.getJSON('index2.php', params, function(data, textStatus){               
            isneedtoKillAjax = false; // set to false
            // Do your actions based on result (data OR textStatus)
        }); 

        function checkajaxkill(){

            // Check isneedtoKillAjax is true or false, 
            // if true abort the getJsonRequest

            if(isneedtoKillAjax){
                myAjaxCall.abort();
                alert('killing the ajax call');                 
            }else{
                alert('no need to kill ajax');
            }
        }
    }

回答by Chris Laplante

The timeout option proposed by Galen is the best way. If you want an alternate method, you could record the time when the request was initiated and, in your callback, compare it to the current time. Ignore the result if a certain amount of time has elapsed. Of course this would not cancel the request.

Galen 提出的超时选项是最好的方法。如果你想要一个替代方法,你可以记录请求发起的时间,并在你的回调中,将它与当前时间进行比较。如果经过一定时间,则忽略结果。当然,这不会取消请求。