我正在使用AJAX调用JSON文件,并尝试使用DOM将数据以表格格式放置。它根本不起作用。有人可以帮我用DOM创建表的逻辑吗?我尝试编写的错误代码在这里。 `
// AJAX request
var xhttp = new XMLHttpRequest();
var fulldata;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
fulldata = JSON.parse(this.responseText);
}
}
xhttp.open("GET", "https://raw.githubusercontent.com/attainu-falcon/falcon-course-
module/master/coding-challenges/data/books.json", true);
xhttp.send();
// creating table using DOM
var table = document.createElement('table');
table.setAttribute('class', 'tbl')
document.querySelector('.div2').appendChild(table);
// from here nothing is working and I don't understand what to do.
for(var i=0; i<fulldata.length; i++){
var rows = document.createElement('tr');
document.querySelector('.tbl').appendChild(rows);
var cols = document.createElement('td');
document.querySelector('.tbl tr').appendChild(cols);
rows.innerHTML = <td>fulldata[i].author</td>;
rows.innerHTML = <td>fulldata[i].language</td>;
}
这里的主要问题是您的代码似乎期望网络请求是同步的(即,在发出fulldata
函数调用之后填充了xhttp.send()
)。
为了使代码按要求工作,您应该改为在onreadystatechange
函数处理程序的“内部”建立表(即,在填充fulldata
的那一点)。一种解决方法如下:
function buildTable(json) {
var table = document.createElement('table');
table.classList.add('tbl')
document.querySelector('.div2').appendChild(table);
json.forEach(({ author, language }) => {
let row = table.insertRow()
row.insertCell().innerText = author
row.insertCell().innerText = language
})
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Call our build table function here, when a response is recieved
buildTable(JSON.parse(this.responseText));
}
}
xhttp.open("GET", "https://raw.githubusercontent.com/attainu-falcon/falcon-course-module/master/coding-challenges/data/books.json", true);
xhttp.send();
这里是working example-希望对您有帮助!