【发布时间】:2009-11-01 13:00:02
【问题描述】:
如何使用 JavaScript 检查文件是否存在(在这种情况下,我想检查一个 xml 文件)?
【问题讨论】:
标签: javascript file
如何使用 JavaScript 检查文件是否存在(在这种情况下,我想检查一个 xml 文件)?
【问题讨论】:
标签: javascript file
如果你使用 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);
【讨论】:
如果文件位于为包含 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');
【讨论】:
Javascript 并没有真正的文件处理功能。最好的办法是检查服务器端并将一些上下文发送回客户端。
如果你想要超级 hacky,你可以调用 xmlHttpRequest(如果你使用 jQuery,请查看 $.ajax 函数)
调用 $.ajax 后,您可以使用成功/错误处理程序来确定要执行的操作。如果文件不存在,它应该会报错。
这当然不是推荐的方法。
【讨论】:
我没有足够的声誉来发布 cmets,所以请注意,在 Anwar Chandra 的回答(非 jQuery 版本)中,您最终必须致电:
myrequest.send();
另外,HEAD 方法会更好地“检查文件是否存在”,因为您不需要从服务器读取整个文件。
【讨论】: