有没有办法用JS刷新table i apps脚本中的数据?

问题描述 投票:0回答:1

我想每 5 秒刷新一次表中的数据 - Google Sheet 中的表每小时更新几次 - 如果有必要 - 可以刷新完整的 div。

如果没有办法做到这一点 - 我尝试刷新整页:

document.addEventListener('DOMContentLoaded', () => {
          setTimeout(function() {window.location.reload()}, 10000)
          google.script.run
            .withSuccessHandler(populateTable)
            .getNearlyTPT()
        });

但它返回给我一张空白页。

表格看起来像:

数据1 数据2 数据3
任务 16:30 完成

代码如下:

Code.gs 中的代码:

function getNearlyTPT(){
  let ss = SpreadsheetApp.openByUrl('xxx');
  let ws = ss.getSheetByName("xxx");
  const today = new Date();
  let h = today.getHours();
  let m = today.getMinutes();
  let data = ws.getRange('H3:J').getValues().filter(r => r[0] && r[1] > h +":"+m);
  return data
}

代码:

function makeRow(row) {
          let tr = document.createElement('tr');
          row.forEach(cell => {
            let td = document.createElement('td');
            td.textContent = cell;
            tr.appendChild(td)
          });
          return tr;
        }


        function populateTable(data) {
          let tasks = document.getElementById('tpt');
          data.forEach(row => {
            let tr = makeRow(row);
            tasks.appendChild(tr);
          });
        }

        document.addEventListener('DOMContentLoaded', () => {
          google.script.run
            .withSuccessHandler(populateTable)
            .getNearlyTPT()
        });

以及 html 中的 div:

<div id = "tpt2Table">
      <table>
        <thead>
          <tr>
            <th>Data 1</th>
            <th>Data 2</th>
            <th>Data 3</th>
          </tr>
        </thead>
        <tbody id="tpt"></tbody>
      </table>
    </div>
javascript html google-sheets google-apps-script
1个回答
0
投票

您应该利用 Google Apps 脚本的

setInterval
每 5 秒调用您的
getNearlyTPT
函数,以获取更新的数据。 使用 JavaScript 的 DOM 操作动态更新 HTML 中的现有表格行。

HTML(已修改):

<div id="tpt2Table">
  <table>
    <thead>
      <tr>
        <th>Data 1</th>
        <th>Data 2</th>
        <th>Data 3</th>
      </tr>
    </thead>
    <tbody id="tpt"></tbody>
  </table>
</div>

<script>
  // Call getNearlyTPT initially to populate the table
  google.script.run
    .withSuccessHandler(populateTable)
    .getNearlyTPT();

  function populateTable(data) {
    let tableBody = document.getElementById('tpt');
    tableBody.innerHTML = ''; // Clear existing rows

    data.forEach(row => {
      let tr = document.createElement('tr');
      row.forEach(cell => {
        let td = document.createElement('td');
        td.textContent = cell;
        tr.appendChild(td);
      });
      tableBody.appendChild(tr);
    });
  }

  // Refresh data every 5 seconds
  setInterval(function() {
    google.script.run.getNearlyTPT().then(populateTable);
  }, 5000);
</script>

使用

populateTable
进行的初始
google.script.run
调用会用数据填充表格。
setInterval
函数使用 Promise
getNearlyTPT
每 5 秒触发一次
(then)
来处理异步响应。 更新的数据被传递到 populateTable,它会清除现有的表体
(innerHTML = '')
并用新数据重建它。

© www.soinside.com 2019 - 2024. All rights reserved.