javascript 我可以使用 AJAX + 跨域 + jsonp 测试 URL 是否可访问吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9670875/
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
Can I test if URL is reachable using AJAX + cross-domain + jsonp?
提问by jmend
I'm using JQuery to fetch information from an URL and display it on my page asynchronously. The URL comes from other domain, so I use JSONP to get the data. That works fine.
我正在使用 JQuery 从 URL 获取信息并将其异步显示在我的页面上。URL 来自其他域,所以我使用 JSONP 来获取数据。这很好用。
However, when the remote URL is down (which happens once in a while) my page hangs as JQuery AJAXdoesn't call the 'success' or 'error' functions.
但是,当远程 URL 关闭(偶尔发生)时,我的页面会挂起,因为JQuery AJAX不会调用“成功”或“错误”函数。
I'm using JQuery 1.7.
我正在使用 JQuery 1.7。
My code looks like:
我的代码看起来像:
$.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);
}
});
If "somePage" is up, then I see the message "ok". If "somePage" is not reachable, then I don't see anything.
如果“somePage”已启动,那么我会看到消息“ok”。如果无法访问“somePage”,那么我什么也看不到。
Any ideas on how can I get "error" function get called? Or more importantly, how to detect if the cross-domain URL is reachable?
关于如何调用“错误”函数的任何想法?或者更重要的是,如何检测跨域URL是否可达?
Is that even possible?
这甚至可能吗?
Thanks,
谢谢,
回答by Rafay
add a timeout
添加一个 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");
}
});