I'm trying to pull in some JSON data via AJAX for a Greasemonkey script.
Here's what I have:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var xmlresult = JSON.parse(this.response);
// this works
console.log(xmlresult);
}
};
xmlhttp.open("GET", "https://raw.githubusercontent.com/mledoze/countries/master/countries.json", true);
xmlhttp.send();
// this doesn't work
console.log(xmlresult);
For some reason, xmlresult
is always empty. If I dump out the response in the console directly, there's clearly data in the response, but if I try to do anything with it outside of my if block, it doesn't exist.