Wyniki skryptu Java nie są wyświetlane w formacie HTML

Nov 30 2020

Napisałem kod GAS, aby sprawdzić, czy pracownik jest w środku, czy nie (pobieranie danych z arkuszy Google). Dziennik konsoli daje mi właściwą odpowiedź, ale kiedy klikam przycisk, odpowiedź nie pojawia się na początku. Czy możesz mi pomóc rozwiązać problem, w którym popełniłem błąd?

<div>
<script>
 function onStatus(notify) { 
 
 var employee = "John Peter";
 
 var ss = SpreadsheetApp.getActiveSpreadsheet();        
 var mainSheet = ss.getSheetByName("MAIN");
 var data = mainSheet.getDataRange().getValues();
 
 
   for (var j = 0; j < data.length; j++){
    var row = data[j];
    var mainSheet2 = row[4];
    var mainSheet3 = row[0];
    var status = (mainSheet2 =="IN" && mainSheet3 == employee) ; 
    if (status == true){
      var notify = employee +" You Are In"
      
      return notify;
 
  }
      }
document.getElementById('status').innerHTML= notify;       
      }
     
    </script>
<button onclick="onStatus()">Check Status</button>

 <font color='Green' id="status" ></font>
</div>

Odpowiedzi

4 Diego Nov 30 2020 at 10:49

Firma Google udostępnia bardzo dobry przewodnik dotyczący komunikacji klient-serwer, z którym zdecydowanie polecam zapoznać się, aby lepiej zrozumieć, jak to działa.

Nie możesz umieścić kodu skryptów aplikacji (np. SpreadsheetApp.getActiveSpreadsheet()) W skryptach frontendu. Ten kod musi być uruchamiany przez serwer skryptów aplikacji w zapleczu, a następnie wywołujesz go za pomocą google.script.runwywołania.

Code.gs

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('Index');
}

function checkStatus() { 
  var employee = "John Peter";
  var ss = SpreadsheetApp.getActiveSpreadsheet();        
  var mainSheet = ss.getSheetByName("MAIN");
  var data = mainSheet.getDataRange().getValues();
  
  for (var j = 0; j < data.length; j++){
    var row = data[j];
    var mainSheet2 = row[4];
    var mainSheet3 = row[0];
    var status = (mainSheet2 =="IN" && mainSheet3 == employee) ; 
    if (status == true){
      return employee + " You Are In";
    }
  }
}

Index.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <div>
      <button onclick="onStatus()">Check Status</button>
      <font color='Green' id="status" ></font>
    </div>

    <script>
      function onStatus() {
        google.script.run
          .withSuccessHandler(updateStatus) // Send the backend result to updateStatus()
          .checkStatus(); // Call the backend function
      }
  
      function updateStatus(notify) {
        document.getElementById('status').innerHTML= notify;
      }
    </script>
  </body>
</html>