从JQuery图像中的error()事件检索HTTP状态代码. [英] Retrieve HTTP Status Code from error() Event in JQuery image.

查看:54
本文介绍了从JQuery图像中的error()事件检索HTTP状态代码.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过Javascript加载图片,但是知道404错误和500错误之间的区别(如果失败).

I need to load an image by Javascript, but know the difference between a 404 and 500 error if it fails.

我有代码将图像加载到"img"标签中,如下所示:

I have code to load an image into an 'img' tag like the below:

var img = $('<img />').attr('src', url)
    .load(function() {
        // Do something.
    })
    .error(function(ev) {
        // What sort of error?
    });

在error()函数中,我似乎无法分辨出错误是500还是404.有什么办法吗?

In the error() function, I don't seem able to tell whether the error was a 500 or a 404. Is there any way of doing this?

推荐答案

处理并测试 http状态页像这样

DEMO

var img = $('<img />')
    .load(function() {
        // Do something.
    })
    .error(function(jqXHR, error, errorThrown) {  
       if(jqXHR.status&&jqXHR.status==404)
       {
            alert(jqXHR.responseText); 
       }
       else
       {
           alert("Something went wrong");
       }
    })
    .attr('src', url);

这篇关于从JQuery图像中的error()事件检索HTTP状态代码.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆