javascript - 如何使用 Google Apps 脚本中的 google.script.run 将 JS 对象传递给服务器函数?
问题描述
我想使用 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 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
属性。所以例如,也请修改如下。
从:
template.config = { bob: 'Bob', charlie: 'Charlie' };
到:
template.config = { bob: 'Bob', charlie: 'Charlie', name: 'sample' };
参考:
如果我误解了您的问题并且这不是您想要的方向,我深表歉意。
推荐阅读
- office-js - Outlook加载项的cors问题
- bash - 在bash中测试变量的内容看是否为空
- python - 如何从命令行将 dict 传递给 Robot Framework 变量
- ios - 如何在一个 TableView 中有两种不同类型的 UITableViewCell 时在 UITableView 中设置 UICollectionView 数据源
- datetime - '7/4/18' 被 Date() 解析为 'Thu Jul 04 00:00:00 GMT-04:00 1918'
- javascript - 验证匹配不能为空
- php - 使用 PHP 访问数组中的对象属性
- bottlenose - 瓶颈 HTTP 错误 403:禁止
- javascript - NGXS 重用状态(扩展状态类)
- css - 如何使用属性来定义带有 React 样式组件的径向渐变?