gpt4 book ai didi

javascript - 解析 JSON 文件时 undefined reference

转载 作者:行者123 更新时间:2023-12-03 11:28:21 26 4
gpt4 key购买 nike

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

我遇到的问题是“stuff”未定义,我不明白为什么。

最佳答案

您正在异步代码中使用同步代码。 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]);
}
}

关于javascript - 解析 JSON 文件时 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26828138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com