我正在尝试从我的API请求中获取输出(room_presences.occupied),并将其另存为html页中表格的“已占用”列中的字段。如何保存API请求输出并将其添加到表中?
在某些情况下,它是一个房间占用检测系统。我正在尝试将房间的占用状态保存到一个表格中,该表格显示在html页面(下方)中的“占用”列中。我将其显示在控制台上以显示请求的工作。
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest();
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'http://localhost:3000/api/room_presences', true);
request.onload = function () {
// Begin accessing JSON data here
var data = JSON.parse(this.response);
data.forEach(room_presences => {
// Log each Occupancy
console.log(room_presences.occupied);
});
}
// Send request
request.send();
答案 0 :(得分:0)
如果我正确理解了您的问题,这是一个解决方案,其要点:
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest();
// Open a new connection, using the GET request on the URL endpoint
request.open("GET", "http://localhost:3000/api/room_presences", true);
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response);
// have a dom node that would contain the table
const tableContainerEl = document.querySelector("#table_id")
for (let i = 0; i < data.length; i++) {
// skip the header row with +1
const rowIndex = i + 1;
const row = tableContainerEl.rows[rowIndex];
// we hit an empty row,
// so there is probably no more rows with content
// get out of the loop
if (!row) {
break;
}
const bookedCellIndex = 1;
const bookedCell = row.cells[1];
bookedCell.innerHTML = data[i].occupied ? "YES" : "NO";
const occupancyCellIndex = 4;
const occupancyCell = row.cells[occupancyCellIndex];
occupancyCell.innerHTML = data[i].occupied;
}
};
// Send request
request.send();