使用JavaScript检查服务器上是否存在图像? [英] Check if image exists on server using JavaScript?
本文介绍了使用JavaScript检查服务器上是否存在图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用javascript有一种方法可以判断服务器上是否有资源可用?例如,我将图像1.jpg - 5.jpg加载到html页面中。我想每分钟调用一次JavaScript函数,大致会执行以下的临时代码...
Using javascript is there a way to tell if a resource is available on the server? For instance I have images 1.jpg - 5.jpg loaded into the html page. I'd like to call a JavaScript function every minute or so that would roughly do the following scratch code...
if "../imgs/6.jpg" exists:
var nImg = document.createElement("img6");
nImg.src = "../imgs/6.jpg";
想法?谢谢!
推荐答案
你可以使用类似的东西:
You could use something like:
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
显然你可以使用jQuery / similar来执行你的HTTP请求。
Obviously you could use jQuery/similar to perform your HTTP request.
$.get(image_url)
.done(function() {
// Do something now you know the image exists.
}).fail(function() {
// Image doesn't exist - do something else.
})
这篇关于使用JavaScript检查服务器上是否存在图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文