2015-05-11 32 views
0

我已經創造了一些小JT代碼,但它給了我錯誤JSON解析錯誤:無法讀取屬性

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'); 

,這裏是我的JSON文件

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

在命令生活一切順利的話,但是當我運行此代碼時,出現錯誤

Uncaught TypeError: Cannot read property 'nouns' of undefined

+0

另見#1 FAQ:[訪問/處理對象,數組或JSON(http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Roberto

回答

4

多重錯誤。最基本的是你的代碼忽略XMLHttpRequest是異步的,並且不會像「常規」函數那樣返回一個值。在這裏閱讀:How to make a function wait until a callback has been called using node.js。該TL; DR是你必須傳遞一個「回調函數」到你解析法和「返回」使用值函數,而不是使用返回語句。谷歌的「JavaScript回調」,並閱讀一些教程,如果這個概念對你來說是新的!

您還有一些小錯誤,如從Parse返回result,但從未實際將result設置爲任何內容。另外words正在被分配在多個地方,這種方式並沒有什麼意義。但是,當解決同步/異步問題時,這些事情都會消失。

編輯:

基本上修復看起來像這樣:

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! 
    }); 
}} 
+0

Hi @Jakob。請你能告訴我更多,我該如何解決它?謝謝 – Gor

+0

有一個錯誤遺漏的類型錯誤:回調不是一個函數 – Gor

+0

謝謝你,一切順利的話 – Gor