如何检查图片是否存在给定的URL?


77

我想检查图像是否存在使用jQuery。

例如我如何检查该图像是否存在

http://www.google.com/images/srpr/nav_logo14.png 

支票必须给我200或状态还可以

--------------编辑-------------------

var imgsrc = $(this).attr('src');
var imgcheck = imgsrc.width;


if (imgcheck==0) {
alert("You have a zero size image");
} else { //do rest of code }

谢谢让


1
您有权利发布和接受对自己问题的答案。
sje397

Answers:


77

使用这样的error处理程序:

$('#image_id').error(function() {
  alert('Image does not exist !!');
});

如果无法加载该图像(例如,由于所提供的URL中不存在该图像),则显示警报:

更新:

我认为使用:

$.ajax({url:'somefile.dat',type:'HEAD',error:do_something});

足以检查404。

更多阅读:

更新2:

您的代码应如下所示:

$(this).error(function() {
  alert('Image does not exist !!');
});

不需要这些行,也不会检查远程文件是否存在:

var imgcheck = imgsrc.width;    

if (imgcheck==0) {
  alert("You have a zero size image");
} else { 
  //execute the rest of code here 
}

@sAc我没有图像的ID,只想检查文件是否存在,否则继续执行剩余的代码
X10nD 2010年

@Jean:请在您的问题中发布您的代码,以了解您的需求或需求。
Sarfraz

如果您查看此网址google.com/images/srpr/nav_logo14.png,如果图像存在,则必须给我尺寸,或状态为200 / ok
X10nD 2010年

@sAc imgsrc.width似乎不起作用。我正在使用图片网址获取宽度...正在通过图片网址,由警报检查
X10nD 2010年

1
在大多数情况下,您需要向AJAX调用添加async:false,否则它将以随机间隔返回,并且可能导致脚本编写不稳定。
兰斯·克利夫兰2012年

34
$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function(){
            //do something depressing
    },
    success: function(){
            //do something cheerful :)
    }
});

来自:http : //www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06


15
警告:您会收到错误消息:[XMLHttpRequest无法加载not.on.your.domain.com/someimg.jpg。所请求的资源上不存在“ Access-Control-Allow-Origin”标头。]因此,仅当映像位于服务器上时,这才是一个不错的选择。
Twelve24

13

如果不存在,则加载默认图像或处理错误

$('img[id$=imgurl]').load(imgurl, function(response, status, xhr) {
    if (status == "error") 
        $(this).attr('src', 'images/DEFAULT.JPG');
    else
        $(this).attr('src', imgurl);
    });

这是正确的答案,您也可以使用$('<img>').load(url ...
Lightbeard

5

用例

$('#myImg').safeUrl({wanted:"http://example/nature.png",rm:"/myproject/images/anonym.png"});

API:

$.fn.safeUrl=function(args){
  var that=this;
  if($(that).attr('data-safeurl') && $(that).attr('data-safeurl') === 'found'){
        return that;
  }else{
       $.ajax({
    url:args.wanted,
    type:'HEAD',
    error:
        function(){
            $(that).attr('src',args.rm)
        },
    success:
        function(){
             $(that).attr('src',args.wanted)
             $(that).attr('data-safeurl','found');
        }
      });
   }


 return that;
};

注意 : rm这里指风险管理。


另一个用例:

$('#myImg').safeUrl({wanted:"http://example/1.png",rm:"http://example/2.png"})
.safeUrl({wanted:"http://example/2.png",rm:"http://example/3.png"});
  • ' http://example/1.png':如果不存在' http://example/2.png'

  • ' http://example/2.png':如果不存在' http://example/3.png'


4

这里

// when the DOM is ready
$(function () {
  var img = new Image();
  // wrap our new image in jQuery, then:
  $(img)
    // once the image has loaded, execute this code
    .load(function () {
      // set the image hidden by default    
      $(this).hide();
      // with the holding div #loader, apply:
      $('#loader')
        // remove the loading class (so no background spinner), 
        .removeClass('loading')
        // then insert our image
        .append(this);
      // fade our image in to create a nice effect
      $(this).fadeIn();
    })
    // if there was an error loading the image, react accordingly
    .error(function () {
      // notify the user that the image could not be loaded
    })
    // *finally*, set the src attribute of the new image to our image
    .attr('src', 'images/headshot.jpg');
});

2

jQuery 3.0已删除 .error。现在是正确的语法

$(this).on('error', function(){
    console.log('Image does not exist: ' + this.id); 
});

0

为了处理图像存在的延迟加载,我在jQuery-

$('[data-src]').each(function() {
  var $image_place_holder_element = $(this);
  var image_url = $(this).data('src');
  $("<div class='hidden-classe' />").load(image_url, function(response, status, xhr) {
    if (!(status == "error")) {
      $image_place_holder_element.removeClass('image-placeholder');
      $image_place_holder_element.attr('src', image_url);
    }
  }).remove();
});

原因:如果使用$image_place_holder_element.load()方法,它将在元素上添加响应,因此将div随机删除并删除它是一个很好的解决方案。希望它对尝试实现延迟加载以及url检查的人有用。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.