我正在开发一个应用程序,将用户的 Facebook 个人资料图片(http://graph.facebook.com/(fb id)/图片)嵌入到 img 标签中。而且它在大多数情况下都有效。但是,当我请求个人资料图片时,我偶尔会收到 400 错误( see this )
有什么方法可以使用 Javascript/JQuery 检测这些 400 错误吗?现在它们显示为损坏的图像......
最佳答案
使用 onerror
事件这非常简单。
我们可以简单地在 JavaScript 中创建一个新图像并为其附加两个事件 - onload
和 onerror
。然后设置图像 src
将使浏览器下载图像,如果它是真实图像,则触发 onload
事件,如果不是,则触发 onerror
事件。
var img = new Image();
// This URL will return an image an fire `onload`
img.src = 'http://placekitten.com/300/300';
// Replace the line above with this one to load a fake/unavailable image, which will fire the `onerror` event.
// img.src = 'http://mybrokenurl';
img.onload = function() {
document.body.appendChild(img);
}
img.onerror = function() {
alert('Error loading image');
}
关于javascript - 检测并处理img标签内的400错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13452065/