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

时光总嘲笑我的痴心妄想 提交于 2019-12-19 07:15:48

问题


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.

However, when the remote URL is down (which happens once in a while) my page hangs as JQuery AJAX doesn't call the 'success' or 'error' functions.

I'm using 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.

Any ideas on how can I get "error" function get called? Or more importantly, how to detect if the cross-domain URL is reachable?

Is that even possible?

Thanks,


回答1:


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



来源:https://stackoverflow.com/questions/9670875/can-i-test-if-url-is-reachable-using-ajax-cross-domain-jsonp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!