Answer the question
In order to leave comments, you need to log in
How to display the elements of a JSON array?
Given an array
[
{
"id": 1,
"name": "Allen, Miss. Elisabeth Walton",
"age": 29,
},
{
"id": 2,
"name": "Allison, Master. Hudson Trevor",
"age": 50,
}
]
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
let myArr = JSON.parse(this.responseText);
myArr.forEach((elem, index, arr) => {
console.log(elem.name);
document.querySelector('.wrapper').innerHTML = elem.name;
});
}
};
xmlhttp.open("GET", "http://***/data.json", true);
xmlhttp.send();
Answer the question
In order to leave comments, you need to log in
1. The (elem, index, arr)
second and third parameters are optional.
2. .innerHTML
- overwrites everything that you output into the same element. Use appendChild at least.
fetch('" http://***/data.json "', {
method: 'GET',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
}). then(r=>r.json()).then(r=>{
r.forEach(function (item) {
let span=document.createElement('span');
span.innerText=item.name;
document.body .appendChild(span);
document.body.appendChild(document.createElement('br'));
})
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question