I have this code:
...
function init() {
getdata();
}
var txt;
function getdata() {
var xhr = new XMLHttpRequest();
xhr.open('GET',myurl, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) if (xhr.responseText) {
txt = xhr.responseText;
}
}
xhr.send();
console.log(txt);
}
...
<body onload="init();">
...
Why can’t I get txt value? Please help.
forgot to mention – all of this happens in background page, i dont have any other pages at the moment. i tried console via extensions overview for background page, but that console doesnt output anything.. :((
The XHR request is asynchronous, so when you log
txtto console immediately after sending it, the request hasn’t completed yet sotxtisundefined.Either set it be run synchronously by setting
asynctofalsein theopencommand, or just stickconsole.log(txt)in the function you have bound to theonreadystatechangeevent already.