javascript - JSON parse error: Cannot read property -
i have created little jt code, gives me error
function mind(){ var request = "request"; var reply = "reply"; var words = ''; this.reply = function(){ if(request == words.nouns[0].noun){ reply = words.nouns[0].noun; } else reply = this.words.nouns[0].noun; } this.setrequest = function(req){ request = req; } this.getreply = function(){ return reply; } this.parse = function(u){ var xmlhttp = new xmlhttprequest(); var url = u; var result; xmlhttp.onreadystatechange = function() { if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { words = json.parse(xmlhttp.responsetext); } } xmlhttp.open("get", url, true); xmlhttp.send(); return result; } this.construct = function(){ words = this.parse('mind/words.json'); }} var mind = new mind(); mind.parse('mind/words.json');
and here json file
{ "nouns": [ {"noun": "child"}, {"noun": "father"} ] }
in command live goes well, when run code, appears error
uncaught typeerror: cannot read property 'nouns' of undefined
mutliple errors. fundamental 1 code ignores xmlhttprequest async, , wont return value in same way "regular" functions. read here: how make function wait until callback has been called using node.js. tl;dr have to pass in "callback-function" parse-method , "return" value using function, instead of using return-statement. google "javascript callbacks" , read few tutorials if concept new you!
you have minor errors, returning result
parse
, never setting result
anything. words
being assigned in multiple places in way doesn't make sense. both of these things go away when solve sync/async issues.
edit:
essentially fix looks this:
this.parse = function(u, callback){ // "callback" new var xmlhttp = new xmlhttprequest(); var url = u; var result; xmlhttp.onreadystatechange = function() { if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { words = json.parse(xmlhttp.responsetext); callback(null, words); // we're "returning" words here } } xmlhttp.open("get", url, true); xmlhttp.send(); // no return statement here! } this.construct = function(){ this.parse('mind/words.json', function(error, words) { // here can use words! }); }}
Comments
Post a Comment