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

Can I test if URL is reachable using AJAX + cross-domain + jsonp?

本文关键字:是否 访问 URL 测试 可以使 AJAX+ 跨域 +jsonp 我可以      更新时间:2023-09-26

我使用JQuery从URL中获取信息,并将其异步显示在页面上。URL来自其他域,所以我使用JSONP来获取数据。这很好。

然而,当远程URL关闭时(这种情况偶尔发生),我的页面会挂起,因为JQueryAJAX不调用"成功"或"错误"函数。

我使用的是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",则我看不到任何内容。

关于如何调用"error"函数,有什么想法吗?或者更重要的是,如何检测跨域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");
        }
    });

演示