You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script中如何将gs变量传入HTML输入框并正常显示?

问题原因

google.script.run是异步执行的,直接调用它不会立即返回testGetFieldName()的结果,而是返回undefined,这就是输入框显示undefined的核心原因。

解决方案

方案1:使用HTML模板直接注入值(推荐)

这种方式在服务器端渲染页面时就把目标值插入,页面加载完成后直接显示内容,无需异步等待。

修改code.gs的testSetValue函数:

function testGetFieldName(){
  var fieldName = 'Account';
  return fieldName;
}

function testSetValue(){
  var html = HtmlService.createTemplateFromFile('index');
  // 将testGetFieldName的返回值绑定到模板变量
  html.fieldName = testGetFieldName();
  var output = html.evaluate()
      .setTitle('MySidebar')
      .setWidth(400)
      .setSandboxMode(HtmlService.SandboxMode.IFRAME);
  SpreadsheetApp.getUi().showSidebar(output);
}

修改index.html,直接在input的value属性中使用模板变量:

<!DOCTYPE html>
<html>
<head>
  <base target="_top">
</head>
<body>
  <input type="text" id='textValue' name='textValue' value='<?= fieldName ?>'/>
</body>
</html>

方案2:使用异步回调处理返回值

如果需要在页面加载后动态获取值,可以利用google.script.run的withSuccessHandler方法,在服务器返回结果后更新输入框。

保持code.gs不变,修改index.html的脚本部分:

<!DOCTYPE html>
<html>
<head>
  <base target="_top">
</head>
<body>
  <input type="text" id='textValue' name='textValue' value=''/>
  <script>
    // 调用服务器函数,成功返回后执行回调更新输入框
    google.script.run
      .withSuccessHandler(function(result) {
        document.getElementById('textValue').value = result;
      })
      .testGetFieldName();
  </script>
</body>
</html>

注:第二种方法中,输入框会先显示空值,等服务器返回结果后才会更新为Account。

内容的提问来源于stack exchange,提问作者whytili

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 18:48:24