我如何检查我的服务器上的文件是否存在jQuery或纯JavaScript?
当前回答
一种类似的和最新的方法。
$.get(url)
.done(function() {
// exists code
}).fail(function() {
// not exists code
})
其他回答
我使用这个脚本添加替代图像
function imgError()
{
alert('The image could not be loaded.');
}
HTML:
<img src="image.gif" onerror="imgError()" />
http://wap.w3schools.com/jsref/event_onerror.asp
如果你使用Babel transpiler或Typescript 2,下面是如何用ES7的方式来做:
async function isUrlFound(url) {
try {
const response = await fetch(url, {
method: 'HEAD',
cache: 'no-cache'
});
return response.status === 200;
} catch(error) {
// console.log(error);
return false;
}
}
然后在你的其他异步作用域中,你可以很容易地检查url是否存在:
const isValidUrl = await isUrlFound('http://www.example.com/somefile.ext');
console.log(isValidUrl); // true || false
这并没有解决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="">
首先创建函数
美元。UrlExists =函数(url) { var http = new XMLHttpRequest(); http。open('HEAD', url, false); http.send (); 还http.status ! = 404; }
使用函数后,如下所示
如果($.UrlExists(“urlimg”)){ 照片 = “IMG1.jpg”; }else{ 照片 = “IMG2.jpg”; } $(''<img>).attr('src',photo);
异步调用查看文件是否存在是更好的方法,因为它不会因为等待服务器的响应而降低用户体验。如果调用.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/
推荐文章
- 如何在JavaScript中获得时区名称?
- 在JSON键名中哪些字符是有效的/无效的?
- jQuery中的live()转换为on()
- 如何区分鼠标的“点击”和“拖动”
- IE9是否支持console.log,它是一个真实的功能吗?
- Node.js同步执行系统命令
- 如何转义JSON字符串包含换行字符使用JavaScript?
- jQuery等价于JavaScript的addEventListener方法
- jQuery需要避免的陷阱
- JavaScript中变量字符串的XML解析
- 用jQuery切换DIV背景图像
- 'React'指的是一个UMD全局,但当前文件是一个模块
- 为什么useState不触发重新渲染?
- 如何使用回调与useState挂钩在反应
- 网络请求失败