javascript - AJAX response is empty when I try to access any of its properties -


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

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -