简体   繁体   English

Javascript检查文件是否存在

[英]Javascript check whether a file exists

I am attempting to work out whether an image exists in javascript using the code below: 我正在尝试使用以下代码计算图像是否存在于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>";
            }
        });

On the 404 pages my console log shows the fail message, however on the pages returning 200 I am not getting the success message. 在404页上,我的控制台日志显示失败消息,但是在返回200的页面上,我没有收到成功消息。

I'm hoping someone can advise me on where I'm going wrong! 我希望有人可以向我建议我要去哪里了!

Thanks 谢谢

By looking at what you are actually doing, it might be wiser for you to not do this by ajax and instead rely on Image , which will throw an error if the returned data is not an (understood by browser) image, too. 通过查看您的实际操作,最好不要使用ajax来执行此操作,而应该依赖Image ,如果返回的数据也不是(浏览器可以理解的)图像,这也会引发错误

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM