且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用JavaScript检查图像URL为404

更新时间:2022-01-25 07:23:53

jQuery Ajax:

jQuery Ajax:

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function()
    {
        //file not exists
    },
    success: function()
    {
        //file exists
    }
});

JavaScript:

Javascript:

function UrlExists(url)
{
    var http = new XMLHttpRequest();
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}

图像检查:

function ImageExist(url) 
{
   var img = new Image();
   img.src = url;
   return img.height != 0;
}

其他:

$.get(url)
    .done(function() { 
        // exists code 
    }).fail(function() { 
        // not exists code
    })

HTML:

<img src="image.gif" onerror="imgError()" />

function imgError()
{
alert('The image could not be loaded.');
}