如何使用JavaScript检查文件是否存在? [英] How can I check existence of a file with JavaScript?

查看:63
本文介绍了如何使用JavaScript检查文件是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I check an existence of a file (It is an xml file that I would like to check in this case) with JavaScript?

推荐答案

如果你正在使用jQuery,你可以尝试加载文件

if you're using jQuery, you can try to load the file

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

如果您不使用jQuery:

if you're not using 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); 

这篇关于如何使用JavaScript检查文件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆