我正在尝试使用 JavaScript 将图像附加到页面:
image = document.createElement('img');
image.onload = function(){
document.body.appendChild(image);
}
image.onerror = function(){
//display error
}
image.src = 'http://example.com/image.png';
用户必须经过身份验证才能看到此图像,如果没有经过身份验证,我想显示一条错误消息。不幸的是,服务器没有返回 HTTP 错误消息,而是将请求重定向到(大部分)空页面,因此我收到了HTTP 200
,但是警告Resource interpreted as Image but transferred with MIME type text/html
并且什么也没有显示。
我该如何处理这个案子?如果用户未经身份验证,我无法更改网络服务器提供的服务。
In the image.onload
事件监听器,检查是否image.width
and image.height
都为零(最好image.naturalWidth
and image.naturalHeight
,当它们受到支持时)。
如果宽度和高度都为零,则图像被视为无效。
Demo: http://jsfiddle.net/RbNeG/ http://jsfiddle.net/RbNeG/
// Usage:
loadImage('notexist.png');
function loadImage(src) {
var image = new Image;
image.onload = function() {
if ('naturalHeight' in this) {
if (this.naturalHeight + this.naturalWidth === 0) {
this.onerror();
return;
}
} else if (this.width + this.height == 0) {
this.onerror();
return;
}
// At this point, there's no error.
document.body.appendChild(image);
};
image.onerror = function() {
//display error
document.body.appendChild(
document.createTextNode('\nError loading as image: ' + this.src)
);
};
image.src = src;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)