使用Javascript检查本地磁盘上是否存在.htm文件
当包含Javascript代码的使用Javascript检查本地磁盘上是否存在.htm文件,javascript,Javascript,当包含Javascript代码的.htm文件在本地加载(而不是从web服务器加载)时,如何使用Javascript检查本地磁盘上是否存在.htm文件?本文可能有助于: 这是:假设htm文件位于同一个域上,您可以执行以下操作: function UrlExists(url) { var http = new XMLHttpRequest(); http.open('HEAD', url, false); http.send(); return http.status!=404; }
.htm
文件在本地加载(而不是从web服务器加载)时,如何使用Javascript检查本地磁盘上是否存在.htm
文件?本文可能有助于:
这是:假设htm文件位于同一个域上,您可以执行以下操作:
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
由于域安全限制,这在一些浏览器(如Chrome)上的本地文件系统上不起作用。此解决方案适用于大多数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;
}
跨浏览器,还是IE?正常的网页安全性或受信任的站点?我只需将fSuccess分配修改为:fSuccess=Boolean(client&&client.responseText&&client.status!=404);酷。当文件系统的状态为404时,client.responseText是什么?根据不同的浏览器以及内容是本地还是Web服务器,您可能会返回“0”或“200”以获得成功。用不同的浏览器测试真假情况。我不知道为什么这个解决方案需要这么长时间,但它确实非常有效!谢谢