我有一個簡單的 web 應用程式,它顯示一個按鈕,當用戶單擊時,它將打開一個顯示網站的新視窗。我想要做的是當用戶單擊按鈕時,它將從我的谷歌表中獲取值并基于該值打開一個新視窗。然后,webapp 將使用新值更新谷歌表中的值。
例如:如果我的谷歌表中的值是“谷歌”,它會打開一個視窗到“www.google.com”,然后將谷歌表值更新為“其他網站”。

每當用戶單擊按鈕時,我都成功地創建了更新 google 作業表上的值的功能,但我無法從 code.gs/google 作業表中獲取值到我的 Javascript。請幫忙。
這是我的 code.gs:
var url = "url"; //mygooglesheet url
var web = "";
function doGet(e) {
let tmp = HtmlService.createTemplateFromFile("index");
return tmp.evaluate();
}
function setWebsite () {
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("website");
web = ws.getRange(1,1,1,1).getValue();
if (web === "Google") {
ws.getRange(1,1,1,1).setValue("Youtube");
}
else if (web === "Youtube") {
ws.getRange(1,1,1,1).setValue("Facebook");
}
else {
ws.getRange(1,1,1,1).setValue("Google");
}
}
function getWebsite() {
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("website");
var web = ws.getRange(1,1,1,1).getValue();
return web;
}
我的 index.html:
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Please Click Below</h1>
<!-- <h2><?=web?>:</h2> -->
<button id = "btn" type="submit" >Open Window</button>
<script>
document.getElementById("btn").addEventListener("click", doStuff);
var web = "";
function doStuff() {
google.script.run.getWebsite(); //dont know for sure if this is needed or not
google.script.run.setWebsite();
web = <?=web?>; //dont know for sure if this is needed or not
if (web === "Google") {
window.open("https://www.google.com/");
}
else if (web === "Youtube") {
window.open("https://www.youtube.com/");
}
else {
window.open("https://www.facebook.com/");
}
}
</script>
</body>
</html>
現在,我的 web 應用程式只打開一個新視窗到“facebook.com”并更新到代碼中的下一個值。我試過“google.script.run.withSuccessHandler(onSuccess).getWebsite()”但沒有成功從code.gs獲取變數值,請幫忙。
謝謝你。
uj5u.com熱心網友回復:
問題:
您希望使用getWebsite()單擊按鈕時回傳的 URL 打開一個新選項卡。
解決方案:
為了處理由google.script.run呼叫的服務器端函式回傳的資料,請使用成功處理程式。此處理程式呼叫的函式將傳遞服務器端函式 ( getWebsite())回傳的值作為引數。
代碼示例:
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Please Click Below</h1>
<button id = "btn" type="submit" >Open Window</button>
<script>
document.getElementById("btn").addEventListener("click", doStuff);
function doStuff() {
google.script.run.withSuccessHandler(openWebsite).getWebsite();
}
function openWebsite(web) {
if (web === "Google") {
window.open("https://www.google.com/");
} else if (web === "Youtube") {
window.open("https://www.youtube.com/");
} else {
window.open("https://www.facebook.com/");
}
}
</script>
</body>
</html>
筆記:
如果回傳的資料getWebsite()應該在頁面首次加載和單擊按鈕之間保持靜態,您還可以使用Mike Steelson提到的方法,使用模板腳本。
uj5u.com熱心網友回復:
在html中,在腳本部分,寫
<? var web = getWebsite(); ?>
并擦除 google.script.run.getWebsite();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/374810.html
上一篇:將多個非空行復制到新作業表
