簡體   English   中英

如何使用 Google Apps Script 中的 google.script.run 將 JS 對象傳遞給服務器函數?

[英]How to pass a JS object to a server function using google.script.run in Google Apps Script?

我想使用 Google Apps 腳本將對象傳遞給服務器函數。 但是我在這樣做時遇到了問題。

<?= config.bob ?>
<button type="button" onclick="google.script.run.sayHiObject(<?= config ?>)">
  Run Bob
</button>

當我單擊標有Run Bob的按鈕時,我希望看到一個警告提示,內容為:

嗨,鮑勃!

但相反,它說:

嗨,未定義!

這個頁面說:

合法參數是 JavaScript 基元,如 Number、Boolean、String 或 null,以及由基元、對象和數組組成的JavaScript 對象和數組。 [強調我的]

所以,我認為可以傳遞一個對象。 但是,下面顯示的演示僅證明可以通過這種方式傳遞字符串。 對象似乎有問題。

我究竟做錯了什么?

圖 1. 演示。 Run AliceRun Charlie成功地將字符串作為參數傳遞。 但是Run Bob未能將對象作為參數傳遞。

在此處輸入圖片說明

代碼.gs
 var TITLE = 'Say hi to:'; var HTML_FILENAME = 'index'; var ui = SpreadsheetApp.getUi(); function handleEdit(e) { var template = HtmlService.createTemplateFromFile(HTML_FILENAME); template.alice = 'Alice'; template.config = { bob: 'Bob', charlie: 'Charlie' }; var htmlOutput = template.evaluate(); ui.showModalDialog(htmlOutput, TITLE); } function sayHi(name) { var msg = 'Hi, ' + name + '!'; ui.alert(msg); } function sayHiString(name) { sayHi(name); } function sayHiObject(config) { sayHi(config.name); }
索引.html
 <!DOCTYPE html> <html> <body> <?= alice ?> <button type="button" onclick="google.script.run.sayHiString(<?= alice ?>)"> Run Alice </button> <?= config.bob ?> <button type="button" onclick="google.script.run.sayHiObject(<?= config ?>)"> Run Bob </button> <?= config.charlie ?> <button type="button" onclick="google.script.run.sayHiString(<?= config.charlie ?>)"> Run Charlie </button> </body> </html>

這個答案怎么樣? 請將此視為幾種可能的答案之一。

template.config = { bob: 'Bob', charlie: 'Charlie' , name: "sample"}; 用作<?= config ?><?= config ?>變成[object Object] 這樣,就會出現這樣的問題。 另一方面, <?= config.charlie ?>變成'Charlie'這是一個字符串。 這樣,腳本就可以工作了。 所以請使用字符串類型作為值。

為了運行你的腳本,下面的修改怎么樣?

修改后的腳本:

從:

<button type="button" onclick="google.script.run.sayHiObject(<?= config ?>)">

到:

<button type="button" onclick="google.script.run.sayHiObject(JSON.parse(<?= JSON.stringify(config) ?>))">

而且,在您的腳本中, { bob: 'Bob', charlie: 'Charlie' }沒有name屬性。 所以例如,也請修改如下。

從:

template.config = { bob: 'Bob', charlie: 'Charlie' };

到:

template.config = { bob: 'Bob', charlie: 'Charlie', name: 'sample' };

參考:

如果我誤解了您的問題並且這不是您想要的方向,我深表歉意。

嗨,嘗試將config更改為config.bob

<button type="button" onclick="google.script.run.sayHiObject(<?= config ?>)">

像這樣

<button type="button" onclick="google.script.run.sayHiObject(<?= config.bob ?>)">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM