首页 > 解决方案 > 如何使用 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 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>

标签: javascripttemplatesgoogle-apps-script

解决方案


这个答案怎么样?请认为这只是几个可能的答案之一。

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' };

参考:

如果我误解了您的问题并且这不是您想要的方向,我深表歉意。


推荐阅读