Fetch data from text file
onload method
document.getElementById('button').addEventListener('click', loadData);
function loadData(){
// Create an XHR object
const xhr = new XMLHttpRequest();
//OPEN - type, url/file, async
xhr.open('GET', 'data.txt', true);
// Onload if status equals to 200
xhr.onload = function(){
if(this.status === 200){
document.getElementById('output').innerHTML = this.responseText;
}
}
// XHR Send
xhr.send();
}
readyState Values
0: request not initialized 1: server connection established 2: request reveived 3: processing request 4: request finished and response is ready
readyState Method
document.getElementById('button').addEventListener('click', loadData);
function loadData(){
// Create an XHR object
const xhr = new XMLHttpRequest();
//OPEN - type, url/file, async
xhr.open('GET', 'data.txt', true);
// Optional - ised for spinners / loaders
xhr.onprogress = function(){
console.log('READYSTATE', xhr.readyState);
}
xhr.onreadystatechange = function(){
console.log('READYSTATE', xhr.readyState);
if(this.readyState === 4 && this.status === 200){
document.getElementById('output').innerHTML = `<p class="lorem">${this.responseText}</p>`;
}
}
xhr.onerror = function(){
console.log('Request error ...');
}
// XHR Send
xhr.send();
}
Leave a Reply