使用 Google Apps Script 開發 Web 應用/資料到電子表格
外觀
如果你從使用者那裡收集了一些資料(可能是來自一個input標籤或其他地方),並且你想要將這些資料儲存到你的電子表格中,那麼你必須將它們傳送到伺服器端,即使你正在使用客戶端來處理所有使用者介面。
步驟如下:
- 從使用者調整的 html 元素中獲取資料
- 可能需要稍微修改資料(例如,修剪任何尾隨或前導空格)
- 使用魔法醬:
google.script.run! - 處理來自伺服器的任何響應
以下是一個簡單的從 textarea 元素中獲取資料的方法,當用戶點選“傳送”時執行:
<textarea id="mytextarea"></textarea>
<button type="button" onClick="grabtext()">send</button>
<script>
function grabtext(){
var text = document.getElementById('mytextarea').value; // note you don't use innerHTML
// here's where'd you do something with that text
}
</script>
一旦你有一些資訊要傳送到伺服器,你必須以某種方式將其傳送到那裡。這就是神奇的 google.script.run 的用武之地!
基本上,你可以透過呼叫**伺服器端**的函式來發送一些資料,該函式可以在那裡執行一些操作,然後返回一些響應。
以下是一個基於上面示例的示例。我們獲取使用者輸入的內容,並將它們新增到(附加的)電子表格中的工作表中
<textarea id="mytextarea"></textarea>
<button type="button" onClick="grabtext()">send</button>
<script>
function grabtext(){
var text = document.getElementById('mytextarea').value; // note you don't use innerHTML
google.script.run.addRowToSheet(text);
}
</script>
同時在伺服器端(因此在 code.gs 中,而不是新增到 main.html 的 javascript 中)
function addRowToSheet(s) { // you can call what's passed anything you want. You don't have to call it "text"
var ss = SpreadsheetApp.getActive(); // grabs the associated spreadsheet
var sheet = ss.getSheetByName("Sheet1");
sheet.appendRow([s]); // appendRow needs an array like ["first column info", "second column info", ...]
}
通常你會想從伺服器那裡收到一些回覆。這就是 withSuccessHandler 的作用。基本上,你告訴 javascript 你想要執行的伺服器函式**和**當有東西返回時應該執行的客戶端函式。語法很奇怪,但它確實有效。
以下是一個增強了最後一個示例的示例,讓使用者知道資料已儲存到電子表格中
<textarea id="mytextarea"></textarea>
<button type="button" onClick="grabtext()">send</button>
<div id="callthiswhateveryouwant"></div>
<script>
function grabtext(){
var text = document.getElementById('mytextarea').value; // note you don't use innerHTML
google.script.run.withSuccessHandler(dealWithIt).addRowToSheet(text);
}
function dealWithIt(returnvalue){ // you can call the return value whatever you want. Often you'll see people calling it "e"
document.getElementById('callthiswhateveryouwant').innerHTML="From the server: "+returnvalue;
}
</script>
同時在伺服器端(因此在 code.gs 中,而不是新增到 main.html 的 javascript 中)
function addRowToSheet(s) { // you can call what's passed anything you want. You don't have to call it "text"
var ss = SpreadsheetApp.getActive(); // grabs the associated spreadsheet
var sheet = ss.getSheetByName("Sheet1");
sheet.appendRow([s]); // appendRow needs an array like ["first column info", "second column info", ...]
return "holy cow it worked!";
}