解析JSON文件时未定义的引用

时间:2014-11-09 12:26:31

标签: javascript json parsing xmlhttprequest

我真的很陌生,所以请耐心等待。我必须解析以这种方式构造的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();

我得到的问题是“东西”未定义,我无法弄清楚原因。

1 个答案:

答案 0 :(得分:1)

您正在异步代码中使用同步代码。 request.onreadystatechange是回调,因此在console.log之前调用request.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]);
          }
    }