【问题标题】:Is it possible to catch failed IMG loads when the server sends HTML instead of image data?当服务器发送 HTML 而不是图像数据时,是否可以捕获失败的 IMG 加载?
【发布时间】:2014-08-22 02:22:39
【问题描述】:

我有一个网站链接到其他网站上的不同图片。有时这些图像已被删除或域不再存在等。为了不显示这些图像并删除它们,我使用 jQuery 来执行此操作:

 // catch image load errors
$( "img" ).error(function() { 

 // read out image source:
 var src = $(this).attr('src');

// post the source to the server for the image to be removed    
 $.post("/pajax/image/notLoaded/", {url:src},
    function success(obj) {

       if(obj.status =='ok'){
            console.log('removed: '+src);
        }

      },
   "json" );

 // hide the image & its container div
    $( this ).hide();
    $( this ).closest(".item-img").hide();

这适用于不再存在且未发送数据的图像。但是,通常会发送足够多的 HTML 页面,在这种情况下 jQuery 不会抛出错误,但控制台会显示“资源解释为图像但使用 MIME 类型文本/html 传输:”

有没有办法用 jQuery 来捕捉它?

【问题讨论】:

    标签: javascript jquery html image


    【解决方案1】:

    你的问题和这个很相似:

    jQuery/JavaScript to replace broken images

    我发现以这种方式编写 <img...> 元素比使用 jQuery 并尝试附加事件更可靠:

    <img src="image.png" onerror="this.style.display='none';"/>
    

    【讨论】:

    • 然后更改onerror处理程序以指向您的函数来处理通知服务器。
    【解决方案2】:

    我不知道 jQuery 如何分配onerror,但是当 MIME 类型不匹配时,我成功获取/处理错误。

    JSFiddle example.

    如果您仍然无法使用它,我的下一个建议是发送 AJAX 请求并尝试检索 MIME 类型。不过,我敢肯定,如果你是 hotlinking,它不会起作用。

    你可以这样做:

    var url = document.getElementsByTagName('img')[0].src
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.send(null);
    
    console.log(xhr.getAllResponseHeaders());
    //or
    console.log(xhr.getResponseHeader("content-type"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 2013-08-12
      • 2014-02-24
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多