【发布时间】: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