【问题标题】:XMLHttpRequest to gather JSON data to make into table?XMLHttpRequest 收集 JSON 数据以制作表格?
【发布时间】:2018-01-16 13:46:12
【问题描述】:

我正在学习 ajax,但我不确定为什么我的 JSON 数据没有通过表格显示到 html 中?我没有收到控制台错误。我将对象显示到控制台中,因为我放置了一个控制台日志。基本上只需要将每个总统信息显示到标题中的属性列出的表中。

HTML

<form>  
    <label for="name">Name:</label> 
    <input id="name" placeholder="President Name" type="text"> 
    <button type="button" onclick="loadPresidents()">Search for Presidents</button>
    <button type="button">Clear</button>

    <div id="presidentialTable"></div>
</form>

JS

function loadPresidents() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
        var data = this.responseText;
        var jsonResponse = JSON.parse(data);
        console.log(jsonResponse["presidents"]);
        var table = document.createElement('table');
        table.setAttribute('class', 'history');
        var properties = ['number', 'name', 'birthday', 'took office', 'left office'];
        var capitalize = function(s) {
            return s.charAt(0).toUpperCase() + s.slice(1);
        }
        var tr = document.createElement('tr');
        for (var i = 0; i < properties.length; i++) {
            var th = document.createElement('th');
            th.appendChild(document.createTextNode(capitalize(properties[i])));
            tr.appendChild(th);
        }
        table.appendChild(tr);
        var tr, row;
        for (var r = 0; r < jsonResponse["presidents"].length; r++) {
            tr = document.createElement('tr');
            row = data[r];
            for (var i = 0; i < properties.length; i++) {
                var td = document.createElement('td');
                td.appendChild(document.createTextNode(row[properties[i]]));
                tr.appendChild(td);
            }
            table.appendChild(tr);
        }
        document.getElementById('presidentialTable').appendChild(table);
    }
};
xhttp.open("GET", "http://schwartzcomputer.com/ICT4570/Resources/USPresidents.json", true);
xhttp.send();
}

【问题讨论】:

    标签: javascript json ajax html-table xmlhttprequest


    【解决方案1】:

    其实你们很亲近。刚刚做了一些小的修改,结果如下:

    function loadPresidents() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState === 4 && this.status === 200) {
                    var data = this.responseText;
                    var jsonResponse = JSON.parse(data);
                    console.log(jsonResponse["presidents"]);
                    var table = document.createElement('table');
                    table.setAttribute('class', 'history');
                    var properties = ['number', 'name', 'date', 'took_office', 'left_office']; // changed this
                    var capitalize = function(s) {
                        return s.charAt(0).toUpperCase() + s.slice(1);
                    }
                    var tr = document.createElement('tr');
                    for (var i = 0; i < properties.length; i++) {
                        var th = document.createElement('th');
                        th.appendChild(document.createTextNode(capitalize(properties[i])));
                        tr.appendChild(th);
                    }
                    table.appendChild(tr);
                    var tr, row;
                    console.log("jsonResponse", jsonResponse); // changed this
                    for (var r = 0; r < jsonResponse["presidents"].president.length; r++) { // changed this
                        tr = document.createElement('tr');
                        row = jsonResponse["presidents"].president[r]; // changed this
                        for (var i = 0; i < properties.length; i++) {
                            var td = document.createElement('td');
                            td.appendChild(document.createTextNode(row[properties[i]]));
                            tr.appendChild(td);
                        }
                        table.appendChild(tr);
                    }
                    document.getElementById('presidentialTable').appendChild(table);
                }
            };
            xhttp.open("GET", "http://schwartzcomputer.com/ICT4570/Resources/USPresidents.json", true);
            xhttp.send();
        }
    

    我添加了一些内联 cmets 为 // changed this 我想你会看到差异。

    【讨论】:

    • 如果有不清楚的地方,我可以详细解释一下
    • 另外,OP 可能想要创建包含列标题的第二个数组,因为它们与 JSON 中返回的对象属性不同。
    • @ihpar 刚刚完成你所做的工作,看起来我错过了属性标题的下划线。控制台日志正在输出对象,不确定第二个?在for循环中,你进入了json的嵌套,比如调用对象的属性?然后为每个数组添加对象访问?
    • @logan26 总统的回应是这样的格式 {"presidents": { "date": "...", "president": [ { "number": 1, "name": " ...”,“日期”:“...”,“took_office”:“...”,“left_office”:“..”,...},...]} 所以,是的,你是对的你只是缺少下划线。 console.log 只是为了看看响应是什么。在 for 循环中,只访问了 json 对象中键的值。您可以访问键的值,例如 var myObj = {"foo": "bar"}; console.log(myObj["foo"]);
    • @ihpar 谢谢你的帮助!缓慢而坚定地学习。
    猜你喜欢
    • 2015-11-15
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多