且构网

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

使用JavaScript检查服务器上是否存在图像?

更新时间:2023-11-26 12:09:04

你可以使用类似的东西:

You could use something like:

function imageExists(image_url){

    var http = new XMLHttpRequest();

    http.open('HEAD', image_url, false);
    http.send();

    return http.status != 404;

}

显然你可以使用jQuery / similar来执行你的HTTP请求。

Obviously you could use jQuery/similar to perform your HTTP request.

$.get(image_url)
    .done(function() { 
        // Do something now you know the image exists.

    }).fail(function() { 
        // Image doesn't exist - do something else.

    })