首页 > 解决方案 > 如何将 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();

标签: javascriptnode.jsjsonmongodbxmlhttprequest

解决方案


如果我正确理解了您的问题,这是一个解决方案,它的要点:

// 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();

推荐阅读