2010-08-01 14 views
64

Voglio controllare se esiste un'immagine usando jquery.Come verificare se l'immagine esiste con un determinato URL?

Per esempio come faccio a verificare questa immagine esiste

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

l'assegno mi deve dare un 200 o di stato ok

-------------- edited- ------------------

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


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

Grazie Jean

+1

Sei completamente nei tuoi diritti di pubblicare e accettare una risposta alla tua stessa domanda. – sje397

+1

@ sje397 Cosa! ... – X10nD

+2

Vero. Controlla le FAQ. – sje397

risposta

73

Utilizzare il error handler in questo modo:

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

Se l'immagine non può essere caricato (ad esempio, perché non è presente alla URL in dotazione), viene visualizzato l'avviso:

Aggiornamento:

Penso che usando:

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

sarebbe sufficiente a verificare la presenza di un 404.

più letture:

Aggiornamento 2:

Il codice dovrebbe essere simile a questo:

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

Non c'è bisogno di queste righe e che non controllerà se il file in modalità remota in ogni caso:

var imgcheck = imgsrc.width;  

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

@sAc Non ho un ID per le immagini, voglio solo controllare se il file è presente, altrimenti andare avanti per eseguire il codice rimanente – X10nD

+0

@Jean: Inserisci il tuo codice nella tua domanda per vedere cosa hai o come ti serve . – Sarfraz

+0

Se dai un'occhiata a questo URL http://www.google.com/images/srpr/nav_logo14.png, se l'immagine è presente, deve darmi la dimensione, oppure una domanda 200/ok – X10nD

2

Da here:

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

domanda modificata ................ – X10nD

9

se un'immagine predefinita carico doesnt esiste o gestire errore

$('img[id$=imgurl]').load(imgurl, function(response, status, xhr) { 
    if (status == "error") 
     $(this).attr('src', 'images/DEFAULT.JPG'); 
    else 
     $(this).attr('src', imgurl); 
    }); 
27
$.ajax({ 
    url:'http://www.example.com/somefile.ext', 
    type:'HEAD', 
    error: function(){ 
      //do something depressing 
    }, 
    success: function(){ 
      //do something cheerful :) 
    } 
}); 

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

+11

ATTENZIONE: riceverai un errore: [XMLHttpRequest non può caricare http://not.on.your.domain.com/someimg.jpg. Nessuna intestazione 'Access-Control-Allow-Origin-' è presente sulla risorsa richiesta.] Quindi questa è solo una buona scelta se l'immagine è sul tuo server. – Twelve24

4

Use Case

$('#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; 
}; 

Nota: rm significa qui managment rischio.


Un altro caso d'uso:

$('#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': se non esiste 'http://example/2.png'

  • 'http://example/2.png': se non esiste 'http://example/3.png'

Problemi correlati