jQuery Ajax generating image error

0

I have the following code:

<table class="table" id="historico">
  <thead>
    <tr>
      <th>Hora</th>
      <th>Música</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

And the script:

setInterval(function() {

$.ajax({
  url: 'http://cors.io/?http://somdomato.com:8000/played',
  type:'GET',
  success: function(retorno){
    var html = "";
    $("<table>").html(retorno).find('tr').slice(3).each(function () {
      var arrayColuna = [];
      $(this).find('td').each(function () {
        arrayColuna.push("<td>" + $(this).text() + "</td>");
      });
      html += "<tr>" + arrayColuna.slice(0,2) + "</tr>";
    });
    $("#historico > tbody").html(html);
  }
});

}, 10000);

Only this causes errors in the console, for example:

link Failed to load resource: the server responded with a status of 404 (Not Found)

How to avoid this?

    
asked by anonymous 26.11.2016 / 15:22

1 answer

1

You gave this error because your image was not found, make sure you're setting the right path.

Something you can do is check if the image exists and if it does not exist, you can display an image message that is not available, for example:

$('img[data-src]').each(function() {
  var self = $(this);

  self.attr('alt', "Carregando...");
  
  var src = self.attr('data-src');

  var img = new Image();

  img.onload = function() {
    self.attr('src', src);
    self.attr('alt', "");
  }
  img.onerror = function() {
    self.attr('alt', "Imagem não encontrada");
  }
  img.src = src;

});
img {
  width: 200px;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><imgdata-src="path/invalido/img.png" />

<img data-src="http://www.generalpepper.com.br/wp-content/uploads/2013/08/bacon1.jpg"/>

Thedata-srcattributeisonlytoleavesrcinthetagwithoutitbeingloadedbydefaultandhavingasyntaxinHTML5default.

InJqueryI'mcreatingaImagethatrepresentsthe<img/>tag,initIputacallbackinonloadsowhenIloadtheimageputthevalueofdata-srcinsrc<img/>toloadtheimagenormallyandacallbackintheonerrorforwhentheimageisnotfoundputinthealtofthe<img/>amessageof"Not found".

It is necessary to set a minimum height and width for the image if not the alt message does not appear.

    
26.11.2016 / 15:38