我可以使用AJAX +跨域+ jsonp测试URL是否可访问?

jme*_*end 6 javascript ajax jquery cross-domain

我正在使用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);
        }
    });
Run Code Online (Sandbox Code Playgroud)

如果"somePage"已启动,那么我会看到消息"ok".如果"somePage"无法访问,那么我什么都看不到.

关于如何获得"错误"功能的任何想法被调用?或者更重要的是,如何检测跨域URL是否可访问?

这甚至可能吗?

谢谢,

Raf*_*fay 10

添加一个 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");
        }
    });
Run Code Online (Sandbox Code Playgroud)

DEMO

  • jsonp是什么:“ jsonp”表示什么? (2认同)