Kết quả tập lệnh Java không hiển thị trong HTML
Tôi đã viết mã GAS để kiểm tra xem nhân viên có Tham gia hay Không (trích xuất dữ liệu từ Google trang tính). Nhật ký bảng điều khiển cho tôi câu trả lời đúng nhưng Khi tôi nhấp vào nút, câu trả lời không xuất hiện ở giao diện người dùng. Bạn có thể giúp tôi khắc phục sự cố tôi đã làm sai ở đâu không?
<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>
Trả lời
Google cung cấp hướng dẫn Giao tiếp giữa Khách hàng với Máy chủ rất tốt mà tôi thực sự khuyên bạn nên đọc để hiểu rõ hơn về cách hoạt động của tính năng này.
Bạn không thể đặt mã tập lệnh ứng dụng (ví dụ SpreadsheetApp.getActiveSpreadsheet()) trong tập lệnh giao diện người dùng của mình. Mã đó phải được chạy bởi máy chủ tập lệnh ứng dụng trong phần phụ trợ và sau đó bạn sẽ gọi nó bằng cách google.script.rungọi.
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>