【发布时间】:2014-02-21 17:23:50
【问题描述】:
我每天使用 PHP 自动为一个附属网站导入几个 XML 提要(Tradetracker、Daisycon 等)。提要包含来自各种商店的产品。
一切都像魅力一样,除了图像。提要中的图像只是简单地热链接到提供者的图像。这在大多数情况下都有效,但是有时(由于各种原因)图像不再存在,受热链接保护,被更改等等。这会导致浏览器中出现“找不到图像”,这不会看起来不错。
我尝试使用 htaccess 解决此问题,但无论出于何种原因,它都不起作用。我用谷歌搜索并尝试了几个 htacces “脚本”,但都没有成功。我也在图像 URL 中尝试了 JS,但这并没有奏效。我更喜欢 htaccess。
有人有什么建议吗?
使用 htaccess 替换图片
RewriteEngine on
<FilesMatch ".(jpg|png|gif)$">
ErrorDocument 404 "/noimage.jpg"
</FilesMatch>
使用 JS
<img src="image.jpg" onerror="this.onerror=null;this.src='default.jpg'">
更新:工作版
<script type="text/javascript">
jQuery(window).load(function() {
jQuery("img").each(function(){
var image = jQuery(this);
if(image.context.naturalWidth == 0 ||
image.readyState == 'uninitialized'){
jQuery(image).unbind("error").attr(
"src", "noimage.jpg"
);
}
});
});
</script>
【问题讨论】:
-
方便的解决方案,干得好!
标签: javascript image .htaccess http-status-code-404