JS Async: 06. AJAX: State
by istiq20
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX: State</title>
</head>
<body>
<h1 id="response"></h1>
<script>
function displayResponse(json) {
const header = document.getElementById("response");
header.textContent = json.response;
}
const ajax = new XMLHttpRequest();
// ajax.addEventListener("readystatechange", callback)
ajax.onreadystatechange = function (){
console.info(`Ready State Change ${ajax.readyState}`);
};
// ajax.open("GET", "api/hello.json");
ajax.open("GET", "api/salah.json");
ajax.addEventListener("load", function () {
if (ajax.status === 200) {
const json = JSON.parse(ajax.responseText);
displayResponse(json);
} else {
displayResponse({
response: `Terjadi Kesalahan dengan status ${ajax.status}`
})
}
});
ajax.send();
</script>
</body>
</html>
JavaScript
// file: hello.json
{
"sayHello": "Hello Programmer Zaman Now"
}