【问题标题】:Undefined reference when parsing a JSON file [duplicate]解析 JSON 文件时未定义的引用 [重复]
【发布时间】:2015-01-05 19:58:32
【问题描述】:

我对这件事真的很陌生,所以请多多包涵。我必须解析一个以这种方式构造的 json 文件:

    {"elements": [{
            "id": 1,
            "name": "my name",
            "description": "my description",
        }, 
        {
            "id": 2,
            "name": "my name 2",
            "description": "my description 2",
        },

我这样做如下,使用 xmlhttprequest 和 JSON.parse:

//      asynchronous call to open the cards json
        request.open("GET", "../json/stuff.json", true);

//      send request to web server
        request.send();

//      onreadystatechange fires when the request state changes
        request.onreadystatechange = function() {
//            if the readystate is 4 the response from web server is ready
//            if the request status is 200 the status is ok
              if (request.readyState === 4 && request.status === 200 ) {
                 stuff = JSON.parse(request.responseText);
                 console.log("here");
              }
        }

        console.log(stuff[0]);

“request”变量,就像“stuff”一样,在全局范围内定义如下:

var request = new XMLHttpRequest();

我得到的问题是“东西”是未定义的,我不知道为什么。

【问题讨论】:

  • 欢迎来到异步编码的世界。

标签: javascript json parsing xmlhttprequest


【解决方案1】:

您正在异步代码中使用同步代码。 request.onreadystatechange 是回调,因此 console.logrequest.onreadystatechange 之前被调用。所以:

request.onreadystatechange = function() {
        if the request status is 200 the status is ok
          if (request.readyState === 4 && request.status === 200 ) {
             stuff = JSON.parse(request.responseText);
             console.log(stuff[0]);
          }
    }

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 2014-03-20
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多