当向yahoo web服务(http://boss.yahooapis.com/ysearch)发出呼叫以返回数据集时,是否可以设置超时并在其过去后退出例程?jQuery getJSON超时
jQuery.getJSON("http://boss.yahooapis.com/ysearch/...etc",
function (data) {
//result set here
});
当向yahoo web服务(http://boss.yahooapis.com/ysearch)发出呼叫以返回数据集时,是否可以设置超时并在其过去后退出例程?jQuery getJSON超时
jQuery.getJSON("http://boss.yahooapis.com/ysearch/...etc",
function (data) {
//result set here
});
可以使用超时选项
http://api.jquery.com/jQuery.ajax/
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback,
timeout: 3000 //3 second timeout
});
盖伦提出的超时选项是最好的方式。如果你想要一个替代方法,你可以记录请求开始的时间,并且在你的回调中,将它与当前时间进行比较。如果经过一段时间,则忽略结果。当然这不会取消请求。
$.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
}
});
错误回调没有为JSONP请求调用... – Matt 2012-10-03 19:25:19
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');
}
}
}
嗨,很好的答案... – 2012-08-31 07:21:47
我喜欢这个答案的创造性。我其实不知道我可以以这种方式中止getJSON调用,所以谢谢。这适用于我们的应用程序。 – uadrive 2014-05-21 14:56:50
谢谢!什么时候超时被触发的回调? – 2010-11-09 21:29:36
不,这就是为什么当ajax调用返回时...该回调函数将被称为 – Galen 2010-11-09 22:43:25
非常好,但你怎么能把一个事件处理器放在超时? – 2011-05-27 08:21:38