javascript - JSON解析错误: Cannot read property

标签 javascript json

我创建了一些小 jt 代码,但它给了我错误

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"}
    ]
}

在命令 live 中一切顺利,但是当我运行此代码时,出现错误

Uncaught TypeError: Cannot read property 'nouns' of undefined

最佳答案

多个错误。最基本的一个是您的代码忽略了 XMLHttpRequest 是异步的,并且不会以与“常规”函数相同的方式返回值。在这里阅读:How to make a function wait until a callback has been called using node.js 。 TL;DR 是您必须将“回调函数”传递给您的解析方法,并使用该函数“返回”您的值,而不是使用 return 语句。如果这个概念对您来说是新概念,请 Google 搜索“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!
    });
}}

关于javascript - JSON解析错误: Cannot read property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30174479/

相关文章:

javascript - jQuery 新手,简单的弹出窗口脚本,有问题吗?

javascript - 将没有键的值推送到 javascript 数组

java - Android retrofit2 通过 jackson 发送 json

javascript - Highstock 日期时间 xAxis,只能显示全部。没有变焦

javascript - 将时间戳添加到 CSS id

javascript - VueJs 指令双向绑定(bind)

json - 在clojure中访问POST json

php - file_get_contents(JSON) 不适用于有效的 URL

java - 使用 Volley 调用多个服务

javascript - 我有2个POJO的学院和流。学院有一套流。在这种情况下如何使Pojo对应正确的json?