I'm using the code bellow to store everything in a text file into a JavaScript var which than will go into a html id and it will be displayed.
var client = new XMLHttpRequest();
client.open('GET', '/old.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
window.onload = function(){
var lengthOfName = client.length
document.getElementById('output').innerHTML = lengthOfName;
};
but the output
id will show nothing in html.
Can anyone help me with this please?
CodePudding user response:
window.onload
doesn't wait for the AJAX to complete. You should put the AJAX code inside the onload
function, and assign to innerHTML
inside the onreadystatechange
function.
Also, client.length
makes no sense. client
is the XHR object, not an array or string, it doesn't have a length. I think you want client.responseText.length
.
window.onload = function() {
var client = new XMLHttpRequest();
client.open('GET', '/old.txt');
client.onreadystatechange = function() {
alert(client.responseText);
var lengthOfName = client.responseText.length
document.getElementById('output').innerHTML = lengthOfName;
}
client.send();
};