Check image HTTP status codes using jQuery/JS?

2019-02-19 13:30发布

is it possible to check the status codes of images using jQuery/JS?

For example,

img1 = "http://upload.wikimedia.org/wikipedia/commons/thumb/2/26/YellowLabradorLooking_new.jpg/260px-YellowLabradorLooking_new.jpg";

if(statusCheck(img1) == 404){
    /do something
}elseif(statusCheck(img1) == 403){
    //do something else
}elseif(statusCheck(img1) == 304){
    //do something else
}

Thanks

1条回答
Animai°情兽
2楼-- · 2019-02-19 14:15

You can construct an Image object, which isn't affected by cross-origin restrictions:

var image = new Image();
image.src = "http://upload.wikimedia.org/wikipedia/commons/thumb/2/26/YellowLabradorLooking_new.jpg/260px-YellowLabradorLooking_new.jpg"

image.onload = function() {
    alert('Image has loaded');
};

image.onerror = function() {
    alert('Image did not load');
};

Image loading is asynchronous, so making a function that returns the error code won't be a good idea.

Demo: http://jsfiddle.net/Blender/apyL7/

Also, there doesn't seem to be a way to get the response code, so you're limited to knowing only whether the image loaded or not.

查看更多
登录 后发表回答