javascript - AJAX response is empty when I try to access any of its properties -
this question has answer here:
i'm trying pull in json data via ajax greasemonkey script.
here's have:
var xmlhttp = new xmlhttprequest(); xmlhttp.onreadystatechange = function() { if (this.readystate == 4 && this.status == 200) { var xmlresult = json.parse(this.response); // works console.log(xmlresult); } }; xmlhttp.open("get", "https://raw.githubusercontent.com/mledoze/countries/master/countries.json", true); xmlhttp.send(); // doesn't work console.log(xmlresult); for reason, xmlresult empty. if dump out response in console directly, there's data in response, if try outside of if block, doesn't exist.
that because xmlresult local variable in onreadystatechange listener function , it's value won't kept outside use. should do:
var xmlresult; var xmlhttp = new xmlhttprequest(); xmlhttp.onreadystatechange = function() { if (this.readystate == 4 && this.status == 200) { xmlresult = json.parse(this.response); } }; xmlhttp.open("get", "https://raw.githubusercontent.com/mledoze/countries/master/countries.json", true); xmlhttp.send();
Comments
Post a Comment