Skip to content

Instantly share code, notes, and snippets.

@akhyaruu
Created September 13, 2019 09:57
Show Gist options
  • Save akhyaruu/696117d6451a6ae41ef74040c24c363d to your computer and use it in GitHub Desktop.
Save akhyaruu/696117d6451a6ae41ef74040c24c363d to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ajax 2 - Local JSON</title>
</head>
<body>
<button id="button1">Dapatkan User</button>
<button id="button2">Dapatkan Users</button>
<br><br>
<h1>User</h1>
<div id="user"></div>
<h1>Users</h1>
<div id="users"></div>
<script>
document.getElementById('button1').addEventListener('click', loadUser);
document.getElementById('button2').addEventListener('click', loadUsers);
function loadUser() {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'user.json', true);
xhr.onload = function () {
if (this.status == 200) {
let user = JSON.parse(this.responseText);
let output = '';
output += `
<ul>
<li>ID: ` + user.id + `</li>
<li>ID: ` + user.nama + `</li>
<li>ID: ` + user.email + `</li>
</ul>
`;
document.getElementById('user').innerHTML = output;
}
}
xhr.send();
}
function loadUsers() {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'users.json', true);
xhr.onload = function () {
if (this.status == 200) {
let users = JSON.parse(this.responseText);
let output = '';
users.forEach(user => {
document.getElementById('users').innerHTML += `
<ul>
<li>ID: ` + user.id + `</li>
<li>ID: ` + user.nama + `</li>
<li>ID: ` + user.email + `</li>
</ul>
`;
});
}
}
xhr.send();
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment