Thursday 30 May 2019

javascript - JSON parse error: Cannot read property



I have created some little jt code, but it 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 is my json file



{
"nouns": [
{"noun": "child"},
{"noun": "father"}

]
}


In command live all goes well, but when I run this code, appears error




Uncaught TypeError: Cannot read property 'nouns' of undefined



Answer




Mutliple errors. The most fundamental one is that your code ignores that XMLHttpRequest is async, and wont return a value in the same way as "regular" functions. Read about it here: How to make a function wait until a callback has been called using node.js. The TL;DR is that you have to pass in a "callback-function" to your parse-method and "return" your value using that function, instead of using a return-statement. Google for "javascript callbacks" and read a few tutorials if this concept is new to you!



You also have some minor errors, like returning result from Parse, but never actually setting result to anything. Also words is being assigned in multiple places in a way that doesn't really make sense. But both of these things will go away when you solve the sync/async issues.



EDIT:



Essentially the fix looks like this:



this.Parse = function(u, callback){ // this "callback" is 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" the 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 you can use your words!
});
}}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...