Skip to content

Commit 337a85c

Browse files
committed
JSON
1 parent 92e0527 commit 337a85c

File tree

3 files changed

+32
-8
lines changed

3 files changed

+32
-8
lines changed

api/people.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[
2+
{ "name": "john", "age": 25 },
3+
{ "name": "peter", "age": 30 },
4+
{ "name": "anna", "age": 18 },
5+
{ "name": "susan", "age": 19 }
6+
]

app.js

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,40 @@
11
/* To show that data fetching is happening asynchronously (in the background), but not on initial page refresh */
22

3+
/*
4+
- JSON is the string format will "GET" from server or sent from browser "POST"
5+
- Since it is string we will need to "parse" when we get or "stringify" when sent to server
6+
*/
7+
8+
const url = "./api/people.json";
9+
310
const btn = document.querySelector(".btn");
411
btn.addEventListener("click", () => {
5-
getData();
12+
getData(url);
613
});
714

8-
function getData() {
15+
function getData(url) {
916
const xhr = new XMLHttpRequest();
1017

11-
xhr.open("GET", "./api/sample.txt");
18+
xhr.open("GET", url);
1219

1320
/* It gets fired when since ready state changes from 0 to 1 when used open() method */
1421
xhr.onreadystatechange = function () {
1522
// console.log(xhr);
1623
if (xhr.readyState === 4 && xhr.status === 200) {
17-
const paragraph = document.createElement("p");
18-
paragraph.textContent = xhr.responseText;
19-
document.body.appendChild(paragraph);
24+
console.log(xhr.responseText);
25+
26+
const data = JSON.parse(xhr.responseText);
27+
console.log(data);
28+
29+
const displayPeople = data
30+
.map((person) => {
31+
return `<p>${person.name}</p>`;
32+
})
33+
.join("");
34+
35+
const element = document.createElement("div");
36+
element.innerHTML = displayPeople;
37+
document.body.appendChild(element);
2038
} else {
2139
console.log({
2240
status: xhr.status,
@@ -31,4 +49,4 @@ function getData() {
3149
}
3250

3351
// It executes first, since the above functionality works asynchronously by browser, only when JavaScript is free then it takes the data from browser
34-
console.log("hello world");
52+
// console.log("hello world");

index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
</head>
1313
<body>
1414
<h1>AJAX</h1>
15-
<button type="button" class="btn">Show More</button>
15+
<button type="button" class="btn">Show JSON</button>
1616
<!-- Link to JavaScript -->
1717
<script type="module" src="./app.js"></script>
1818
</body>

0 commit comments

Comments
 (0)