gpt4 book ai didi

javascript - image.onError 事件永远不会触发,但图像不是有效数据 - 需要解决方法

转载 作者:行者123 更新时间:2023-12-02 22:53:54 24 4
gpt4 key购买 nike

我正在尝试使用 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并且什么也没有显示。

我该如何处理这种情况?如果用户未经身份验证,我无法更改网络服务器提供的服务。

最佳答案

image.onload 事件监听器中,检查 image.widthimage.height 是否都为零(最好是 image .naturalWidthimage.naturalHeight(如果受支持)。

如果宽度和高度都为零,则图像被视为无效。

演示: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;
}

关于javascript - image.onError 事件永远不会触发,但图像不是有效数据 - 需要解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9809015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com