从图像错误处理程序读取响应头

时间:2013-10-07 09:25:49

标签: javascript jquery javascript-events http-headers

我的页面中有一个<img />元素,并且Javascript会定期更改src属性。

src属性发生变化时,我服务器上的代码会检查:

  1. 是用户登录的?
  2. 图像存在吗?
  3. 然后它会相应地发送响应,包括图片或带有错误标题的回复(状态403 Forbidden404 Not Found)。

    这是我的问题:我使用以下代码处理img错误

    $(function(){
        var $img = $('#test_image');
        $img.on('error',function(e){
            // here, I need to read the headers (at least status code)
            console.log(e);
        }).attr('src','http://example.com/loadimg.php?img=3');
    });
    

    如果用户无法加载图片,因为他的会话已过期或者他尝试加载的图片不存在,我需要显示不同的错误消息

    在哪里可以从处理程序中找到eventObject中的响应标头和/或状态代码?

    谢谢。

    jsfiddle

1 个答案:

答案 0 :(得分:2)

如果您的开销不是很大,您可以发送一个Head请求,以查看错误时返回的内容

var http = new XMLHttpRequest();
http.open('HEAD', url, true); // True is for async
http.send();
if (http.status == 404) {
    //
} else if (http.status == 403) {
    //
} else {
    //
}