javascript - 如何将 API 输出保存到 html 页面中的表中?
问题描述
我正在尝试从我的 API 请求中获取输出 (room_presences.occupied),并将其保存为 html 页面中表格的 Occupied 列中的字段。如何保存 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();
解决方案
如果我正确理解了您的问题,这是一个解决方案,它的要点:
// 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();
推荐阅读
- android - 如何等待异步 AudioTrack.write 完成?
- php - 如何使用 PHP 将来自不同 html 页面的数据连续读取到 JSON 文件中的一个大括号中?
- node.js - 无法区分标准输入原始模式中的向上/向下箭头
- javascript - 将后跟字符的文字反斜杠转换为相应的转义序列
- ruby - 将 ADAL 与 Logstash 自定义插件 const 错误一起使用
- android - 无法在 Expo React Native 项目中连接我的 Android 手机
- c# - LINQ 创建嵌套对象的通用列表
- c# - 如何从c#中的字符串索引中获取char
- mongodb - 如何在 mongodb find 查询中投影日期字符串或对象而不是日期数字字段?
- sas - SAS PROC REPORT 列中的条件输出