Подтвердить что ты не робот

Как проверить, существует ли изображение с данным URL?

Я хочу проверить, существует ли изображение с помощью jquery.

Например, как проверить, что это изображение существует

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

проверка должна дать мне 200 или статус ok

-------------- отредактирован -------------------

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


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

Спасибо Жан

4b9b3361

Ответ 1

Используйте error обработчик следующим образом:

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

Если изображение не может быть загружено (например, поскольку оно отсутствует в указанном URL-адресе), отображается предупреждение:

Update:

Я думаю, используя:

$.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 
}

Ответ 3

если он не содержит изображения загрузки по умолчанию или ошибки обработки

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

Ответ 4

Пример использования

$('#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': if not exist 'http://example/2.png'

  • 'http://example/2.png': if not exist 'http://example/3.png'

Ответ 5

Из здесь:

// 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');
});

Ответ 6

jQuery 3.0 удален .error. Правильный синтаксис теперь

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