I have a JSON data looking like this (it's not an object, it's an array):
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv",
}
]
and a function to get data and display it using AJAX, I use JSON.parse() to get the JSON from string: Initialize a XMLHttpRequest object:
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var jsonObj = JSON.parse(xhttp.responseText);
Add a new element to the document:
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;
}
};
But when I run the browser doesn't display value in the table field, it shows undefined . Is there something wrong? I also changed to use JSON.stringtify(), but the result still didn't change. Please help me to figure out the problem
You should a loop to iterate the array like @Lee Taylor said.
for (var item of jsonObj) {
table += "<td>" + item.name + "</td>"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.