Problems inserting HTML using ajax

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 is not being inserted correctly, type, in tbody ta by opening and closing the <tr> tag and then inserting <td> .

Another thing is that thead does not appear.

    
asked by anonymous 18.03.2015 / 15:06

1 answer

2

Hello, I did a simulation without ajax to make it easy, but the context is the same.

<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.3.min.js"></script><tableclass="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 you only have to replace the fors data with your ajax data and good luck. I hope I have helped

    
18.03.2015 / 16:01