我正在尝试使用以下代码计算javascript中是否存在图像:
var image_url = 'http://www.tester.co.uk/shop/images/product_thumbs/t_' + prod.images.toLowerCase() + '.jpg';
$.ajax({
url: image_url,
type:'HEAD',
error:
function(msg_no){
console.log("fail.");
markup += "<td class='movie-image'><img src='/shop/html_templates/files/images/default-category-image.gif'/></td>";
},
success:
function(msg_yes){
console.log("success.");
markup += "<td class='movie-image'><img src='/shop/images/product_thumbs/t_" + prod.images.toLowerCase() + ".jpg'/></td>";
}
});
在404页面上,我的控制台日志显示失败消息,但是在返回200的页面上我没有收到成功消息。
我希望有人可以告诉我我哪里出错了!
由于
答案 0 :(得分:3)
通过查看您实际在做什么,您可能更明智地不通过ajax
来执行此操作,而是依赖 Image ,这将引发错误< / em>如果返回的数据也不是(浏览器理解的)图像。
var img = new Image();
img.onerror = function (msg_no) {
console.log("fail.");
markup += "<td class='movie-image'><img src='/shop/html_templates/files/images/default-category-image.gif'/></td>";
}
img.onload = function (msg_yes) {
console.log("success.");
markup += "<td class='movie-image'><img src='/shop/images/product_thumbs/t_" + prod.images.toLowerCase() + ".jpg'/></td>";
}
img.src = image_url; // fetch after listeners attached