如何使用JavaScript检查文件是否存在?

pen*_*ake 2 javascript file

如何使用JavaScript检查文件的存在(这是我想在这种情况下检查的xml文件)?

Anw*_*dra 5

如果您使用的是jQuery,则可以尝试加载该文件

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

如果你不使用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); 
Run Code Online (Sandbox Code Playgroud)