【发布时间】:2017-01-24 20:43:51
【问题描述】:
我有一个让xmlhttprequest 获取和解析JSON 的脚本。对于从 JSON 获得的每个值,脚本在前一个 JSON 的 forEach 循环中创建另一个 xmlhttprequest,并尝试从从第二个 JSON 获得的数据中附加 HTML。
我的脚本:
var request;
request = new XMLHttpRequest(); //make request to post-list file
request.open('GET', 'main.json', true); //post-list file is in base folder
request.onload = function () {
var dat;
dat = JSON.parse(request.responseText); //parse the post-list json
dat.forEach(function (data) {
req = new XMLHttpRequest(); //make new request for post-detail file
req.open('GET', data.postid + '.json', true); //path to post-detail file is acquired from post-list file
req.onload = function () {
info = JSON.parse(req.responseText); //parse the post-detail file
// function for page contents
document.getElementsByClassName('main-content')[0].innerHTML += '<div class="post"><h2><a href="/post.html?id=' + info.postid + '">' + info.title + '</a></h2><p>' + info.excerpt + '...</p></div>';
};
});
};
request.send();
我的 HTML:
<!DOCTYPE html>
<html>
<head>
<script src = "js/main.js"></script>
</head>
<body>
<div class="main-content"></div>
</body>
</html>
我的 main.json:
[
{
"postid": "2",
"author": "John Doe"
},
{
"postid": "1",
"author": "John Doe"
}
]
我的1.json:(请求为data.postid.json):
{
"postid": "1",
"author": "Jhon Doe",
"title": "This is the first title.",
"category": [
"Music",
"Lifestyle"
],
"year": "2017",
"month": "Jan",
"date": "24",
"text": "<p>This is post 1 full text.</p><p>This is the second paragraph.</p>",
"excerpt": ""
}
实现:http://embed.plnkr.co/B9v5OZK7yAQykmRStECA/
我的结果:只执行第二个 onload 之外的命令。我无法检查是否成功解析了第二个 JSON。
如果我能在没有 jQuery 的情况下做到这一点,我会很高兴。
【问题讨论】:
标签: javascript json xmlhttprequest