.htm当.htm本地加载包含Javascript代码的文件(而不是从Web服务器)时,如何使用Javascript 检查本地磁盘上是否存在文件?
此解决方案适用于大多数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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6040 次 |
| 最近记录: |