我可以使用AJAX +跨域+ jsonp测试URL是否可访问?
我正在使用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”无法访问,那么我什么都看不到。
关于如何获得“错误”function的任何想法都被调用? 或者更重要的是,如何检测跨域URL是否可访问?
这有可能吗?
谢谢,
添加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"); } });