Check for a [duplicate]

0

I need to check for an image coming from one of the positions of a JSON received via AJAX. Did you understand?

Is there a function equivalent to PHP's file_exists () in Javascript or jQuery?

$.ajax({
  url:'http://www.example.com/verificafotos.json',
  success: function(dados) {
   $.each(dados, function(index,value){
    value['titulo'];
    value['imagem'];

    if( SE O ARQUIVO EXISTIR (value['imagem'])) {
      $('img').src(value['imagem']);
    } else {
      $('img').src('http://www.example.com/imagemalternativa.jpg');
    }

   });
  }
});
    
asked by anonymous 22.02.2018 / 16:49

2 answers

0

With Jquery:

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function()
    {
        //arquiv não existe
    },
    success: function()
    {
        //arquivo existe
    }
});
    
22.02.2018 / 17:02
0

You can check if the image exists by URL by creating a new Image() object and using events such as onload (the image was uploaded) and onerror (the image was not uploaded).

The each would look like this:

$.each(dados, function(index,value){
   var tit = value['titulo'],
       img = value['imagem'],
       imgs = new Image();

   imgs.src = img;

   imgs.onload = function(caminho){
      $('img').attr('src', caminho.path[0].src);
   }

   imgs.onerror = function(caminho){
      $('img').attr('src', 'http://www.example.com/imagemalternativa.jpg');
   }
});
    
23.02.2018 / 00:18