Tengo datos JSON que se ven así (no es un objeto, es una matriz):
[ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv", } ]y una función para obtener datos y mostrarlos usando AJAX, uso JSON.parse() para obtener el JSON de la cadena: Inicialice un objeto XMLHttpRequest:
let xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { var jsonObj = JSON.parse(xhttp.responseText);Agregue un nuevo elemento al documento:
var table='<tr><th>Name</th><th>Email</th></tr>'; table += '<tr><td>' + jsonObj["name"] + '</td><td>' + jsonObj["email"] + '</td></tr>' document.getElementById('demo').innerHTML = table; } };Pero cuando ejecuto el navegador no muestra el valor en el campo de la tabla, muestra undefined . ¿Hay algo mal? También cambié para usar JSON.stringtify(), pero el resultado aún no cambió. Por favor, ayúdame a resolver el problema.
Debería un ciclo para iterar la matriz como dijo @Lee Taylor.
for (var item of jsonObj) { table += "<td>" + item.name + "</td>" }