Problems inserting HTML using ajax

Asked

Viewed 263 times

0

I’m having trouble inserting HTML using ajax

HTML:

<table class="table table-hover">
    <thead id="thead">
        <tr id="tr-thead">
        </tr>
    </thead>
    <tbody id="tbody">
    </tbody>
</table>

ajax :

$.ajax({
  url: url,
  type: 'GET',
  dataType: 'json',
  success: function(data) {
    var colunas = data.result[0][1].data[1].length;
    var linhas = data.result[0][1].data.length;
    for (var x = 0; x <= colunas - 1; x++) {
      //aqui eu coloco meu cabeçalho
      $("#tr-thead").append('<td>'+data.result[0][0][opcao][x]+'</td>');
    }
    for (var x = 0; x <= linhas - 1; x++) {
      $("#tbody").append('<tr>');
      for (var y = 0; y <= colunas - 1; y++) {
        //aqui as linhas com os dados
        $("#tbody").append('<td>'+data.result[0][1].data[x][y]+'</td>');
      }
      $("#tbody").append('</tr>');
    }
  },
  error: function() {
    console.log("error");
  } 
});

The problem is that it’s not being inserted correctly, like, in tbody is opening and closing the tag <tr> and then inserting the <td>.

Another thing tbm is that the thead does not appear.

  • 2

    Why don’t you concatenate everything into a string and then insert it all at once? Depending on the number of records, you will notice a good difference in browser performance.

1 answer

2


Hello I did a simulation without ajax to facilitate, but the context is the same.

<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<table class="table table-hover">
    <thead id="thead"><tr id="tr-thead"></tr></thead>
    <tbody id="tbody"></tbody>
</table>

<script>
$(document).ready(function() {
    // Aqui apenas troquei o td pelo th
    $("#tr-thead").append('<th>th 1</th>');
    $("#tr-thead").append('<th>th 2</th>');
    $("#tr-thead").append('<th>th 3</th>');

    for (var x = 0; x < 3; x++) {
        // Aqui anexo 1 tr ao tbody, já com o /tr com um id únixo
        $("#tbody").append('<tr id="tr-body'+x+'"></tr>');
        newtd = ''; // (re)inicia a variavel dos tds
        for (var y = 0; y < 3; y++) {
            // Aqui concateno todos os tds de um tr
            newtd = newtd.concat('<td>td linha '+x+', coluna '+y+'</td>');
        }
        // Aqui enfim, anexo o td a um tr
        $("#tr-body"+x).append(newtd);
    }
});
</script>

Now only you overwrite the data from Fors by your ajax data and good luck. I hope I helped

  • Thank you @Gê Bender

Browser other questions tagged

You are not signed in. Login or sign up in order to post.