我如何检查我的服务器上的文件是否存在jQuery或纯JavaScript?
当前回答
我使用这个脚本来检查一个文件是否存在(它也处理交叉起源问题):
$.ajax(url, {
method: 'GET',
dataType: 'jsonp'
})
.done(function(response) {
// exists code
}).fail(function(response) {
// doesnt exist
})
请注意,当检查的文件不包含JSON时,会抛出以下语法错误。
未捕获SyntaxError:意外的令牌<
其他回答
这对我来说很管用:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
我使用这个脚本来检查一个文件是否存在(它也处理交叉起源问题):
$.ajax(url, {
method: 'GET',
dataType: 'jsonp'
})
.done(function(response) {
// exists code
}).fail(function(response) {
// doesnt exist
})
请注意,当检查的文件不包含JSON时,会抛出以下语法错误。
未捕获SyntaxError:意外的令牌<
异步调用查看文件是否存在是更好的方法,因为它不会因为等待服务器的响应而降低用户体验。如果调用.open,将第三个参数设置为false(如上面的许多示例,例如http. open)。open('HEAD', url, false);),这是一个同步调用,您会在浏览器控制台中得到一个警告。
更好的方法是:
function fetchStatus( address ) {
var client = new XMLHttpRequest();
client.onload = function() {
// in case of network errors this might not give reliable results
returnStatus( this.status );
}
client.open( "HEAD", address, true );
client.send();
}
function returnStatus( status ) {
if ( status === 200 ) {
console.log( 'file exists!' );
}
else {
console.log( 'file does not exist! status: ' + status );
}
}
来源:https://xhr.spec.whatwg.org/
这并没有解决OP的问题,但对于任何从数据库返回结果的人来说:这里是我使用的一个简单方法。
如果用户没有上传头像,头像字段将为NULL,所以我将从img目录插入一个默认头像图像。
function getAvatar(avatar) {
if(avatar == null) {
return '/img/avatar.jpg';
} else {
return '/avi/' + avatar;
}
}
then
<img src="' + getAvatar(data.user.avatar) + '" alt="">
JavaScript函数检查文件是否存在:
function doesFileExist(urlToFile)
{
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();
if (xhr.status == "404") {
console.log("File doesn't exist");
return false;
} else {
console.log("File exists");
return true;
}
}
推荐文章
- 在数组中获取所有选中的复选框
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- 用jQuery检查Internet连接是否存在?
- 如何使用滑动(或显示)函数在一个表行?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;