I wanted to print a message "This will get printed when state is 4." on the console when the ready state is 4. I knew I could use onload() method, but I was just curious whether or not below snippet could do that... It did not work, but I could not understand why it didn't work
why did it not get printed on console eventhough readyState was 4?
const btn = document.getElementsByTagName("button");
const txtFld = document.querySelector("#add-msg");
btn[0].addEventListener('click', callAjax);
function callAjax(event){
// initializing an object for XMLHttpRequest
const xhr = new XMLHttpRequest();
console.log('XMLHttpRequest has been initialized, state UNSEND: ', xhr.readyState); // readyState will be 0
// to initialize request
xhr.open('GET', 'sample_data.txt', true);
console.log('xhr object is OPENED: ', xhr.readyState); // readyState will be 1
xhr.onprogress = function () {
console.log('LOADING', xhr.readyState); // readyState will be 3
};
xhr.onload = function () {
console.log('DONE', xhr.readyState); // readyState will be 4
};
if(xhr.readyState === 4){
console.log("This will get printed when state is 4.")
}
// sending request
xhr.send(); // state is 2
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>onload() vs onreadystatechange()</title>
</head>
<style>
th, td {
border: 1px solid black;
padding: 1em;
}
</style>
<body>
<button>
click and open console
</button>
</body>
</html>
Aucun commentaire:
Enregistrer un commentaire