我想使用 Google Apps 脚本将对象传递到服务器函数。但我这样做时遇到了问题。
<?= config.bob ?>
<button type="button" onclick="google.script.run.sayHiObject(<?= config ?>)">
Run Bob
</button>
当我单击标记为 Run Bob 的按钮时,我希望看到一条警报提示:
Hi, Bob!
但相反,它说:
Hi, undefined!
Legal parameters are JavaScript primitives like a Number, Boolean, String, or null, as well as JavaScript objects and arrays that are composed of primitives, objects, and arrays. [Emphasis mine]
所以,我认为可以传递一个对象。但是,下面显示的演示仅证明可以通过这种方式传递字符串。该对象似乎有问题。
我做错了什么?
图 1. 演示。 Run Alice 和 Run Charlie 成功地将字符串作为参数传递。但是 Run Bob 无法传递对象作为参数。 代码.gsvar 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
属性(property)。例如,还请修改如下。
来自:
template.config = { bob: 'Bob', charlie: 'Charlie' };
致:
template.config = { bob: 'Bob', charlie: 'Charlie', name: 'sample' };
引用:
如果我误解了您的问题并且这不是您想要的方向,我深表歉意。
关于javascript - 如何在 Google Apps 脚本中使用 google.script.run 将 JS 对象传递给服务器函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60086591/