在JavaScript中检测404代码 [英] Detecting 404 code in JavaScript
本文介绍了在JavaScript中检测404代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要能够在JavaScript中检测到丢失的图像。
I need to be able to detect a missing image in JavaScript.
由于href是由JavaScript计算的,因此无法使用服务器上的PHP。
文件存在时有效的脚本是:
PHP on the server can't be used because the href is computed by JavaScript. Script that works when the file exists is:
Data_ID = _DataRow.getDataItem()["Data_ID"];// Picks up the ID of the data
_HitJPG = document.getElementById("HitJPG");
JPGFileName = _DataRow.getDataItem()["JPGFileName"];
directory = JPGFileName.slice(0, 10);
directory = directory.replace(/-/g, "/");
_HitJPG.innerHTML = "<a href=http://77.88.99.54/data/" + directory + "/" + JPGFileName + " ><h3>JPG File for this Data </h3>" + JPGFileName + "</a>";
在Div中设置InnerHTML之前,如何检测HTTP 404代码?
How can I detect a HTTP 404 code before I set the "InnerHTML" in the Div?
推荐答案
您可以使用 onload
和 onerror
检测是否可以加载图像的事件
You can use the onload
and onerror
events to detect wether or not the image can be loaded
var Data_ID = _DataRow.getDataItem()["Data_ID"];
var _HitJPG = document.getElementById("HitJPG");
var JPGFileName = _SETIDataRow.getDataItem()["JPGFileName"];//"2014-04-29T13-36-27.JPG"
var directory = JPGFileName.slice(0, 10);
directory = directory.replace(/-/g, "/");
var image = new Image();
image.onerror = function() {
// fail - image not available
}
image.onload = function() {
// success - image available
_HitJPG.innerHTML = "<a href=http://77.88.99.54/data/" + directory + "/" + JPGFileName + " ><h3>JPG File for this Data </h3>" + JPGFileName + "</a>";
}
image.src = "http://77.88.99.54/data/" + directory + "/" + JPGFileName
这篇关于在JavaScript中检测404代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文