I am taking a course on javascript and the task was to get JSON data from JSONPLACEHOLDER and display users names. By clicking their names, full data about user should be displayed.
JS code:
const ul = document.querySelector(".list-group"); const h1 = document.querySelector("h1"); function getUsers(renderUsers) { const xhr = new XMLHttpRequest(); xhr.open("GET", "https://jsonplaceholder.typicode.com/users"); xhr.addEventListener("load", () => { const response = JSON.parse(xhr.responseText); renderUsers(response); }); xhr.addEventListener("error", () => { console.log("error"); }); xhr.send(); } function renderUsers(response) { const fragment = document.createDocumentFragment(); response.forEach((user) => { const li = document.createElement("li"); li.classList.add("list-group-item"); li.textContent = user.name; li.addEventListener("click", (e) => { h1.innerHTML = `<h3>Email: ${user.email} <br> Username: ${user.username} <br></h3> Address: <h5>${user.address["street"]}, ${user.address["city"]}, ${user.address["zipcode"]}</h5> </h3>Phone: ${user.phone} </h3>`; }); fragment.appendChild(li); }); ul.appendChild(fragment); } getUsers(renderUsers);
So, I dont know, why infornation is shown. After all, this is not saved anywhere or I don't understand something. Please, tell me the logic where does the information come from by clicking?
Function getUsers
makes a request to https://jsonplaceholder.typicode.com/users
and receives users JSON data in return. Then function renderUsers
gets called, which loops over parsed JSON data and inserts/renders users with full data in html.
More info about XMLHttpRequests
https://www.w3schools.com/xml/xml_http.asp
First sample user info from the request made
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
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.