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