javascript - Java 脚本结果未在 HTML 中显示
问题描述
我写了一个 GAS 代码来检查员工是在还是不在(从谷歌表中提取数据)。控制台日志给了我正确的答案,但是当我点击按钮时,答案没有出现在前端。你能帮我解决我哪里出错了吗?
<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>
解决方案
谷歌提供了一个非常好的客户端到服务器通信指南,我强烈建议你阅读以更好地理解它是如何工作的。
您不能将应用程序脚本代码(例如SpreadsheetApp.getActiveSpreadsheet()
)放在前端脚本中。该代码必须由后端的应用程序脚本服务器运行,然后您将使用 google.script.run
调用来调用它。
代码.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";
}
}
}
索引.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>
推荐阅读
- c# - 如何在 Unity 中将球移动到特定方向?
- javascript - 将标题附加到 D3 树布局会导致错误 (D3)
- python - 需要帮助将字符串从文本文件转换为浮点数
- flutter - 表没有列颤动
- aframe - 关于池的问题,对象没有产生
- java - 在地图中的自定义对象中获取二维数组
- mysql - SQL Management Studio - 让我的光标更高效?
- python-3.x - 使用 GCP Dataflow 和 Apache Beam Python SDK 从 GCS 读取速度非常慢
- java - 如何知道一个arraylist是否包含一个或多个对象以及如何在Java中对该数组中所有对象的值之一求和?
- .net - 测试日志记录的最佳方法?