jQuery:如何为 `$.ajax(dataType:'jsonp'...` 启用 `timeout`?有啥解决方案吗?
Posted
技术标签:
【中文标题】jQuery:如何为 `$.ajax(dataType:\'jsonp\'...` 启用 `timeout`?有啥解决方案吗?【英文标题】:jQuery: How to enable `timeout` for `$.ajax(dataType:'jsonp'...`? Is there any solution?jQuery:如何为 `$.ajax(dataType:'jsonp'...` 启用 `timeout`?有什么解决方案吗? 【发布时间】:2011-06-08 11:14:33 【问题描述】:jQuery:如何为$.ajax(dataType:'jsonp'...
启用timeout
?有什么解决办法吗? http://jsfiddle.net/laukstein/2wcpU/4
$.ajax(
type:"GET",
url:'http://lab.laukstein.com/ajax-seo/.json',
dataType:'jsonp',
timeout:200, // Not working with dataType:'jsonp'
success:function(data)$('#content').html(data.content);,
error:function(request,status,error)$('#content').html('request failed');
);
我不喜欢为此使用一些插件,例如http://code.google.com/p/jquery-jsonp。
【问题讨论】:
复制:***.com/questions/1002367/… 我不想为此使用一些插件,例如code.google.com/p/jquery-jsonp 也许你可以看看插件代码,看看它做了什么,但是我链接到的答案表明这是 JSONP 的限制。 【参考方案1】:宾雅明,
这个 SO 答案应该对您有所帮助:
jQuery ajax (jsonp) ignores a timeout and doesn't fire the error event
基本上,建议使用jquery.jsonp
而不是$ajax
【讨论】:
这与我对问题的评论中链接的同一个问题完全相同。 抱歉,马库斯,现在可以看到了。我开始回答时没有评论:) 我之前已经看过这个答案了。不幸的是,我不想为此使用一些插件,例如code.google.com/p/jquery-jsonp。所以我正在寻找其他解决方案? 不是问题,但它可能不应该被列为问题的答案,而是作为评论。【参考方案2】:这是我的解决方案,setTimeout
和 clearTimeout
http://jsfiddle.net/laukstein/2wcpU/7/
$('#content').ajaxStart(function()
$(this).html('Loading...');
);
var timer=window.setTimeout(function()
$('#content').html('Loading seems to be taking a while. Try again.');
,2000);
$.ajax(
type:"GET",
url:'http://lab.laukstein.com/ajax-seo/.json',
dataType:'jsonp',
success:function(data)
window.clearTimeout(timer);
$('#content').html(data.content);
,
error:function()
window.clearTimeout(timer);
$('#content').html('The request failed. Try to refresh page.');
);
【讨论】:
以上是关于jQuery:如何为 `$.ajax(dataType:'jsonp'...` 启用 `timeout`?有啥解决方案吗?的主要内容,如果未能解决你的问题,请参考以下文章