2012-03-12 50 views
6

我正在使用JQuery從URL中獲取信息並異步顯示在我的頁面上。該URL來自其他域,所以我使用JSONP來獲取數據。這工作正常。我可以使用AJAX +跨域+ jsonp測試URL是否可以訪問嗎?

但是,當遠程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」無法訪問,那麼我什麼都看不到。

關於如何獲得「錯誤」函數的任何想法被調用?或者更重要的是,如何檢測跨域URL是否可達?

這可能嗎?

感謝,

+2

有點關係:** [對於跨域XMLHttpRequest檢測服務器/現場支持?](http://stackoverflow.com/questions/9433949/detect-server-site-support-for-cross-domain-xmlhttprequests)** – hippietrail 2012-03-13 18:39:10

回答

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"); 
     } 
    }); 

DEMO

+0

謝謝!我很高興這很簡單。 – jmend 2012-03-12 17:34:31

+1

什麼是jsonp:「jsonp」表示? – suyash 2016-08-10 13:53:04

相關問題