我如何检查我的服务器上的文件是否存在jQuery或纯JavaScript?
当前回答
当我试图运行这个问题的答案时,我遇到了一个跨域权限问题,所以我去了:
function UrlExists(url) {
$('<img src="'+ url +'">').load(function() {
return true;
}).bind('error', function() {
return false;
});
}
它似乎工作得很好,希望这有助于某人!
其他回答
我使用这个脚本来检查一个文件是否存在(它也处理交叉起源问题):
$.ajax(url, {
method: 'GET',
dataType: 'jsonp'
})
.done(function(response) {
// exists code
}).fail(function(response) {
// doesnt exist
})
请注意,当检查的文件不包含JSON时,会抛出以下语法错误。
未捕获SyntaxError:意外的令牌<
对于客户端计算机,可以通过以下方式实现:
try
{
var myObject, f;
myObject = new ActiveXObject("Scripting.FileSystemObject");
f = myObject.GetFile("C:\\img.txt");
f.Move("E:\\jarvis\\Images\\");
}
catch(err)
{
alert("file does not exist")
}
这是我的程序传输文件到一个特定的位置,并显示警报,如果它不存在
这是我从2020年开始工作的Async纯Javascript
function testFileExists(src, successFunc, failFunc) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState === this.DONE) {
if (xhr.status === 200) {
successFunc(xhr);
} else {
failFunc(xhr);
}
}
}
// xhr.error = function() {
// failFunc(xhr);
// }
// xhr.onabort = function() {
// failFunc(xhr);
// }
// xhr.timeout = function() {
// failFunc(xhr);
// }
xhr.timeout = 5000; // TIMEOUT SET TO PREFERENCE (5 SEC)
xhr.open('HEAD', src, true);
xhr.send(null); // VERY IMPORTANT
}
function fileExists(xhr) {
alert("File exists !! Yay !!");
}
function fileNotFound(xhr) {
alert("Cannot find the file, bummer");
}
testFileExists("test.html", fileExists, fileNotFound);
我不能强迫它返回任何中止、错误或超时回调。 在上面的测试中,每一个都返回一个主状态代码0,所以 我把它们拿掉了。你可以尝试。 我将超时时间设置为5秒,因为默认值似乎太大了。 对于Async调用,如果没有send()命令,它似乎不会做任何事情。
我使用这个脚本添加替代图像
function imgError()
{
alert('The image could not be loaded.');
}
HTML:
<img src="image.gif" onerror="imgError()" />
http://wap.w3schools.com/jsref/event_onerror.asp
这对我来说很管用:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
推荐文章
- 如何在JavaScript中获得时区名称?
- 在JSON键名中哪些字符是有效的/无效的?
- jQuery中的live()转换为on()
- 如何区分鼠标的“点击”和“拖动”
- IE9是否支持console.log,它是一个真实的功能吗?
- Node.js同步执行系统命令
- 如何转义JSON字符串包含换行字符使用JavaScript?
- jQuery等价于JavaScript的addEventListener方法
- jQuery需要避免的陷阱
- JavaScript中变量字符串的XML解析
- 用jQuery切换DIV背景图像
- 'React'指的是一个UMD全局,但当前文件是一个模块
- 为什么useState不触发重新渲染?
- 如何使用回调与useState挂钩在反应
- 网络请求失败