我正在使用 JQuery 从 URL 获取信息并将其异步显示在我的页面上。 URL 来自其他域,因此我使用 JSONP 来获取数据。效果很好。
但是,当远程 URL 关闭时(偶尔会发生),我的页面会挂起jQuery AJAX不调用“成功”或“错误”函数。
我正在使用 JQuery 1.7。
我的代码如下所示:
$.ajax({
type : "GET",
url : "http://otherdomain.com/somePage.html",
data : params,
dataType : "jsonp",
jsonp : "jsonp",
success : function (response, textS, xhr) {
alert("ok");
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("not ok " + errorThrown);
}
});
如果“somePage”已启动,那么我会看到消息“ok”。如果“somePage”无法访问,那么我什么也看不到。
关于如何调用“错误”函数的任何想法?或者更重要的是,如何检测跨域URL是否可达?
这可能吗?
Thanks,
add a timeout
$.ajax({
type : "GET",
url : "http://otherdomain.com/somePage.html",
data : params,
timeout:3000,
dataType : "jsonp",
jsonp : "jsonp",
success : function (response, textS, xhr) {
alert("ok");
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("not ok " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
}
});
DEMO
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)