通常最好尽快修复损坏的图像路径,因为它们会损害网站的可信度。更糟糕的是让用户告诉你这件事。使用 jQuery 和 PHP,您可以让您的页面自动通知您损坏的图像。
PHP
if(isset($_POST['image']))
{
$to = 'errors@yourdomain.com';
$from = 'automailer@yourdomain.com';
$subject = 'Broken Image';
$content = "The website is signaling a broken image!\n\nBroken Image Path: ".stripslashes($_POST['image'])."\n\nReferenced on Page: ".stripslashes($_POST['page']);
$result = mail($to,$subject,$content,'From: '.$from."\r\n");
die($result);
}
我使电子邮件简短而切题;它包含损坏图像的 src 属性和请求它的页面。
jQuery JavaScript
$(document).ready(function() {
$('img').error(function() {
$.post('ajax-image-error-jquery.php', {
image: $(this).attr('src'),
page: window.location.href
}, function() {
//hide the image?
});
});
});
对于每张图片,我们都会监听 error 事件。当发现损坏的图像时,AJAX 请求将发送到上述 PHP 脚本。
当然,如果在您修复图像路径之前页面流量很高,您将收到很多电子邮件。您可能更愿意将错误存储在数据库表中并经常检查。
