2011-03-02 57 views

回答

5

該解決方案適用於大多數所有版本的IE和FF。從本地磁盤運行時無法在Chrome上使用。

我在同步模式下使用XHR和舊的IE ActiveX控件。您可以輕鬆將其轉換爲使用onreadystatechange回調運行異步。

在你自己的Javascript代碼中,只需調用IsDocumentAvailable(「otherfile.htm」),你應該設置。

function IsDocumentAvailable(url) { 

     var fSuccess = false; 
     var client = null; 

     // XHR is supported by most browsers. 
     // IE 9 supports it (maybe IE8 and earlier) off webserver 
     // IE running pages off of disk disallows XHR unless security zones are set appropriately. Throws a security exception. 
     // Workaround is to use old ActiveX control on IE (especially for older versions of IE that don't support XHR) 

     // FireFox 4 supports XHR (and likely v3 as well) on web and from local disk 

     // Works on Chrome, but Chrome doesn't seem to allow XHR from local disk. (Throws a security exception) No workaround known. 

     try { 
      client = new XMLHttpRequest(); 
      client.open("GET", url, false); 
      client.send(); 
     } 
     catch (err) { 
      client = null; 
     } 

     // Try the ActiveX control if available 
     if (client === null) { 
      try { 
       client = new ActiveXObject("Microsoft.XMLHTTP"); 
       client.open("GET", url, false); 
       client.send(); 
      } 
      catch (err) { 
       // Giving up, nothing we can do 
       client = null; 
      } 
     } 

     fSuccess = Boolean(client && client.responseText); 

     return fSuccess; 
    } 
+0

我只需要將fSuccess分配修改爲:fSuccess = Boolean(client && client.responseText && client.status!= 404); – Cornel 2011-03-02 08:15:24

+0

很酷。什麼是client.responseText當狀態404離開文件系統?根據不同的瀏覽器以及內容是本地還是網絡服務器,您可能會返回「0」或「200」以取得成功。用不同的瀏覽器測試真實和虛假的情況。 – selbie 2011-03-02 08:41:45

+0

我不知道爲什麼這個解決方案必須這麼久,但它確實很好!謝謝! – dezman 2013-05-14 21:02:20

0

假設htm文件是在同一個域,你可以這樣做:

function UrlExists(url) { 
    var http = new XMLHttpRequest(); 
    http.open('HEAD', url, false); 
    http.send(); 
    return http.status!=404; 
} 

這不會對工作由於域安全限制,在多個瀏覽器(如Chrome)上使用本地文件系統。

相關問題