我发送一个AJAX请求,并得到一个JSON对象作为响应。我正在尝试使用DOM API将JSON对象中的数据放入表中。目前,它根本不起作用。
有人可以通过这种方式用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
的那一点)。一种解决方法如下:
// Define a helper function that creates and populates a
// table based on the provided json data
function buildTable(rows) {
// Create the table
var table = document.createElement('table');
table.classList.add('tbl');
// Attach the table to document
document.querySelector('.div2').appendChild(table);
// Iterate each row of json data and insert row/cells
// with author and language values of each row
json.forEach(({ author, language }) => {
let row = table.insertRow()
row.insertCell().innerText = author
row.insertCell().innerText = language
})
}
var xhttp = new XMLHttpRequest();
// This function is called when a response is returned
// from the AJAX request. This is the "asynchronous callback"
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// If we reach this point, the request is understood to be
// successful and we process the responseText as JSON and
// build the table
buildTable(JSON.parse(this.responseText));
}
}
// Execute the AJXA request
xhttp.open("GET", "https://raw.githubusercontent.com/attainu-falcon/falcon-course-module/master/coding-challenges/data/books.json", true);
xhttp.send();
这里是working example-希望对您有帮助!