Load table body with JSON. ASPX

0

I have the following table:

<body>
    <table id="datas" align="center">
        <thead>
            <tr>
                <th>Id</th>
                <th>Nombre</th>
                <th>Edad</th>
            </tr>
        </thead>
        <tbody id="cuerpo">

        </tbody>

    </table>
</body>

I have a script that brings me data from a BD to fill in the table:

$("body").ready(function () {

    $.ajax({
        url: "index.aspx/listado",
        method: "POST",
        //data: JSON.stringify(datos),
        //async: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (respuesta) {
            console.log(respuesta.d);

            //LENAR BODY DE TABLE
        }
    });
});

The following is coming to me in respuesta.d :

[{"id":1,"nombre":"Victor","edad":28},
{"id":2,"nombre":"Vix","edad":15},
{"id":3,"nombre":"Viti","edad":30},
{"id":4,"nombre":"Sandro","edad":16},
{"id":5,"nombre":"Carmen","edad":19},
{"id":6,"nombre":"Pedro","edad":20}]

How can I put this data in body of the table.

    
asked by Baker1562 22.11.2018 в 01:18
source

1 answer

1

Here is an example of how you can do it. I was commenting the lines so that the procedure is understood. Any questions queries. Greetings!

Example:

var data =[{"id":1,"nombre":"Victor","edad":28},
{"id":2,"nombre":"Vix","edad":15},
{"id":3,"nombre":"Viti","edad":30},
{"id":4,"nombre":"Sandro","edad":16},
{"id":5,"nombre":"Carmen","edad":19},
{"id":6,"nombre":"Pedro","edad":20}]


for (var i = 0; i < data.length; i++){
    //Agregamos cada item a nuestra tabla
    let item = data[i];
     addRow(item.id, item.nombre, item.edad);
}

function addRow(id, nombre, edad){
 //Primero creamos la fila
 let tblrow = document.createElement("tr");
 //creamos cada columna
 let tdId = document.createElement("td");
 let tdNombre = document.createElement("td");
 let tdEdad = document.createElement("td");
 
 //Asignamos los valores
   tdId.textContent = id;
   tdNombre.textContent = nombre;
   tdEdad.textContent = edad;
   
   //agregamos las columnas a la fila
    tblrow.appendChild(tdId);
    tblrow.appendChild(tdNombre);
    tblrow.appendChild(tdEdad);
   
   //agregamos la fila a la tabla, mas especificamente al body.
    document.getElementById("cuerpo").appendChild(tblrow);
   
}
<table id="datas" align="center">
        <thead>
            <tr>
                <th>Id</th>
                <th>Nombre</th>
                <th>Edad</th>
            </tr>
        </thead>
        <tbody id="cuerpo">

        </tbody>

    </table>
    
answered by 22.11.2018 / 01:57
source