如何在JavaScript中的另一个函数中创建xmlhttprequest和onload函数?

时间:2017-01-24 11:34:22

标签: javascript json xmlhttprequest

我有一个脚本使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的情况下做到这一点,我会很高兴。

1 个答案:

答案 0 :(得分:1)

您忘记在req.send()循环内拨打forEach。如果您不调用它,则永远不会进行HTTP调用。

我还在两个event调用中添加了onload参数,并使用event.target.responseText变量来获取解析的响应

var request; 
request = new XMLHttpRequest(); 
request.open('GET', 'main.json', true); 
request.onload = function (event) { // <-- Add event argument 
    var dat;
    dat = JSON.parse(event.target.responseText); // <-- and use event.target to get the response text
    dat.forEach(function (data) {
        req = new XMLHttpRequest(); 
        req.open('GET', data.postid + '.json', true);
        req.onload = function (event) { // <-- Add event argument 
            info = JSON.parse(event.target.responseText); // <-- and use event.target to get the response text
            var cat = info.category;
            var catl = cat.length;
            var ti = '';
            for (i = 0; i < catl; i++) {
                ti += '<a href="category.html?id=' + cat[i].replace(" ", "-") + '">' + cat[i] + '</a>';
                if (i < catl - 1) {
                    ti += ', ';
                }
            }
            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 class="meta"><a href="/author.html?id=' + info.author.replace(" ", "-") + '">' + info.author + '</a> in ' + ti + ' <i class="link-spacer"></i> ' + info.month + ' ' + info.date + ', ' + info.year + ' <i class="link-spacer"></i> <i class="fa fa-bookmark"></i> ' + info.time + ' min read </div></div>';
        };
        req.send(); // <-- You need to send every inner request, otherwise the HTTP call is never made
    });
};
request.send();

请参阅此处的工作示例:https://plnkr.co/edit/Alewp8nW9aPjlbO0DDi1