javascript 当图像加载失败时,摆脱“加载资源失败:服务器响应状态为 403(禁止)”消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6552617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting rid of the "Failed to load resource: the server responded with a status of 403 (Forbidden)" message when an image fails to load?
提问by Lance Pollard
If an image doesn't exist, or somehow an image just doesn't load, is there a way to make it so this message doesn't show up in the web inspector?
如果图像不存在,或者图像以某种方式无法加载,是否有办法使其不显示在网络检查器中?
Failed to load resource: the server responded with a status of 403 (Forbidden)
加载资源失败:服务器响应状态为 403(禁止)
I have tried these:
我试过这些:
<img src="/path.png" onerror="this.src = '/missing.png'; this.onerror = ''; return true;"/>
<img src="/path.png" onerror="this.src = '/missing.png'; this.onerror = ''; return false;"/>
And I've tried it in jQuery:
我已经在 jQuery 中尝试过:
$(document).ready(function() {
$("img").error(function(event) {
$(this).attr("src", "/missing.png");
return false;
}
});
That message gets output in red before any of these event handlers get access to it, is there not a way to prevent this message from showing up?
在这些事件处理程序中的任何一个访问它之前,该消息以红色输出,有没有办法阻止此消息显示?
Ideally, I would be able to do this:
理想情况下,我将能够做到这一点:
$("img").live("error", function() { $(this).attr("src", "/missing.png"); });
so I don't have to:
所以我不必:
- Write inline javascript like
<img onerror='x'/>
- and it would work on dynamically loaded images.
- 像这样编写内联 javascript
<img onerror='x'/>
- 它适用于动态加载的图像。
采纳答案by Rodaine
Unfortunately you would need to check for the existence of the image prior to adding the <img>
to the DOM. This check would have to occur server-side as far as I know; even attempting to do this with JQuery/AJAX will still result in a 404 or 403 error appearing in the console.
不幸的是,您需要在将图像添加<img>
到 DOM之前检查图像是否存在。据我所知,这项检查必须在服务器端进行;即使尝试使用 JQuery/AJAX 执行此操作仍会导致控制台中出现 404 或 403 错误。