我如何检查我的服务器上的文件是否存在jQuery或纯JavaScript?
当前回答
我使用这个脚本添加替代图像
function imgError()
{
alert('The image could not be loaded.');
}
HTML:
<img src="image.gif" onerror="imgError()" />
http://wap.w3schools.com/jsref/event_onerror.asp
其他回答
您需要做的是向服务器发送一个请求,让它进行检查,然后将结果发回给您。
您试图与哪种类型的服务器通信?您可能需要编写一个小型服务来响应请求。
首先创建函数
美元。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);
这是我从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()命令,它似乎不会做任何事情。
jQuery:
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
编辑:
下面是检查404状态的代码,不使用jQuery
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
小的改变,它可以检查状态HTTP状态码200(成功)。
编辑2:由于sync XMLHttpRequest已弃用,你可以添加一个这样的实用方法来异步执行:
function executeIfFileExist(src, callback) {
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (this.readyState === this.DONE) {
callback()
}
}
xhr.open('HEAD', src)
}
这对我来说很管用:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
推荐文章
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?