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

Javascript 解析JSON文件时未定义的引用,javascript,json,parsing,xmlhttprequest,Javascript,Json,Parsing,Xmlhttprequest,我对这件事真的不熟悉,所以请在这件事上容忍我。我必须解析一个json文件,其结构如下: {"elements": [{ "id": 1, "name": "my name", "description": "my description", }, { "id": 2, "name": "my name 2", "

我对这件事真的不熟悉,所以请在这件事上容忍我。我必须解析一个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();

我遇到的问题是“东西”没有定义,我不知道为什么

您正在异步代码中使用同步代码。
请求.onreadystatechange
是回调,因此在
请求.onreadystatechange
之前调用
控制台.log
。因此:

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]);
          }
    }

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