JS Async: 05. AJAX: Response status
by istiq20
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>AJAX: Response Status</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.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"
}