简体   繁体   中英

Automatically update Google Apps Script webapp

I have a Google web app displaying an HTML dashboard with data pulled in via AJAX. The Spreadsheet is populated using a Google Form and I'd like the data (mock election results) to be updated every 10 seconds or so as votes come in so teachers can see live results.

Here's the relevant portion of the app:

code.gs

function getData() {
  var sheet = ss.getSheets()[3];
  var data = sheet.getDataRange().getValues();
  Logger.log(data);
  return JSON.stringify(data);
}

function doGet() {
  return HtmlService
    .createTemplateFromFile("index")
    .evaluate();
}

HTML template

      function popularVote(data) {
        var getDivs = document.getElementsByClassName("percent");
        var data = JSON.parse(data);

        for(var j=0;j<getDivs.length;j++) {
          getDivs[j].textContent = ((data[j][1]/data[j][2]) * 100).toFixed(1) + "%";
        }
      }
      google.script.run.withSuccessHandler(popularVote).getData();

      <div class="card" id="popular">
          <div class="cand" id="cand1">
            <h2>Candidate:</h2><span class="percent">Loading...</span>
          </div>
          <div class="cand" id="cand2">
            <h2>Candidate:</h2><span class="percent">Loading...</span>
          </div>
          <div class="cand" id="cand3">
            <h2>Candidate:</h2><span class="percent">Loading...</span>
          </div>
        </div>

What I can't figure it out is what actually pulls the data. Is the the success handler polling the server? Or is it the client-side script? Where should I include Utilities.sleep or similar?

It seems like this line is getting the data from the spreadsheet:

google.script.run.withSuccessHandler(popularVote).getData();

You could try wrapping this line in setInterval so that it is called every ten seconds:

setInterval(function(){ 
 google.script.run.withSuccessHandler(popularVote).getData(); 
 }, 10000);

There also may be a Google Apps Script equivalent for setInterval.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM