2009-11-01 13 views

回答

5

,如果你使用jQuery,您可以嘗試加載該文件

$.ajax({ 
    type: "GET", 
    url: "/some.xml", 
    success: function() 
    { /** found! **/}, 
    error: function(xhr, status, error) { 
    if(xhr.status==404) 
     { /** not found! **/} 
    } 
}); 

,如果你不使用jQuery:

function ajaxRequest(){ 
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] 
//Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) 
if (window.ActiveXObject){ 
    for (var i=0; i<activexmodes.length; i++){ 
    try{ 
    return new ActiveXObject(activexmodes[i]) 
    } 
    catch(e){ 
    //suppress error 
    } 
    } 
} 
else if (window.XMLHttpRequest) // if Mozilla, Safari etc 
    return new XMLHttpRequest() 
else 
    return false 
} 

var myrequest=new ajaxRequest() 
myrequest.onreadystatechange=function(){ 
if (myrequest.readyState==4){ //if request has completed 
    if (myrequest.status==200 || window.location.href.indexOf("http")==-1){ 
    // FOUND! 
    } 
} 
} 

myrequest.open('GET', 'http://blabla.com/somefile.xml', true); 
+1

「#somehiddenplace」並不是真正需要的jQuery,你可以使用$ .get,$ .post或$ .Ajax而不需要不必要的標記 – 2009-11-01 13:25:33

+0

@vatos你是對的。謝謝 – 2009-11-01 13:35:42

+0

它已更新。更好地使用$ .ajax – 2009-11-01 13:36:23

4

如果文件位於提供包含JavaScript的頁面,你可以嘗試sending an ajax請求,並驗證返回的狀態碼在同一主機上:

function checkFile(fileUrl) { 
    var xmlHttpReq = false; 
    var self = this; 
    // Mozilla/Safari 
    if (window.XMLHttpRequest) { 
     self.xmlHttpReq = new XMLHttpRequest(); 
    } 
    // IE 
    else if (window.ActiveXObject) { 
     self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

    self.xmlHttpReq.open('HEAD', fileUrl, true); 
    self.xmlHttpReq.onreadystatechange = function() { 
     if (self.xmlHttpReq.readyState == 4) { 
      if (self.xmlHttpReq.status == 200) { 
       alert('the file exists'); 
      } else if (self.xmlHttpReq.status == 404) { 
       alert('the file does not exist'); 
      } 
     } 
    } 
    self.xmlHttpReq.send(); 
} 

checkFile('/somefile.xml'); 
+0

+1使用HEAD請求 – 2009-11-01 15:55:51

0

JavaScript並沒有真正有任何文件處理功能。你最好的選擇是做檢查服務器端並把一些上下文發送回客戶端。

如果你想獲得超級哈克你可以稱之爲一個xmlHttpRequest(如果你使用jQuery來看看在$.ajax功能)

一旦你調用$就可以使用成功/錯誤處理程序確定要做什麼。如果文件不存在,它應該吐出一個錯誤。

這當然不是推薦的方法來做到這一點。

0

我沒有足夠的信譽要發表評論所以讓我注意到,在安華錢德拉的答案(非jQuery的版本),你必須最終調用:

myrequest.send(); 

而且,HEAD方法會更好地「檢查文件的存在」,因爲您不需要從服務器讀取整個文件。

+0

您可能沒有發表評論的聲望,但是您可以編輯'Anwar Chandra的回答。改進答案並提出適當的編輯總結。在3位評論者批准該建議後,您可以獲得+2代表。 – Raju 2016-04-06 00:01:16

+0

很高興知道,謝謝。 – 2016-04-12 13:44:25

相關問題