-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_example.js
More file actions
39 lines (37 loc) · 1.07 KB
/
Copy pathjson_example.js
File metadata and controls
39 lines (37 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const btn = document.querySelector('.btn');
const url = `./api/person.json`;
btn.addEventListener('click', () => {
getData(url);
});
function getData(url) {
// construct xhr
const xhr = new XMLHttpRequest();
// method open get/post/put, url
xhr.open('GET', url);
// untuk perubahan readyState
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// disini dia akan convert ke obj gunakan parse
const data = JSON.parse(xhr.responseText);
// get obj use map
const displayData = data
.map((item) => {
return `<p>${item.name} As ${item.job}</p>`;
})
.join(' ');
// buat element <div></div>
const element = document.createElement('div');
// isi element div dgn displayData
element.innerHTML = displayData;
// add to browser
document.body.appendChild(element);
} else {
console.log({
status: xhr.status,
response: xhr.responseText,
readyState: xhr.readyState,
});
}
};
xhr.send(); // for request to server
}