在How can I add multiple inputs from an HTML UI to a Google Spreadsheet?中,我从最上面的答案中复制了以下脚本,并做了 2个补充,并在下面的脚本中用了注释。
addItem.gs
下面的文件已添加#2
function openInputDialog() {
var html = HtmlService.createHtmlOutputFromFile('Index').setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Add Item');
}
function itemAdd(form) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
//Addition #2
document.getElementById("status_value").innerHTML = "Submitted!";
sheet.appendRow([" ", form.category, form.item, form.manupub, form.details, form.quantity]);
return true;
}
Index.html
以下文件已添加#1
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<br>
<form>
Category:<br>
<input type="text" name="category">
<br>
Item:<br>
<input type="text" name="item">
<br>
Manufacturer or Publisher:<br>
<input type="text" name="manupub">
<br>
Details:<br>
<input type="text" name="details">
<br>
Quantity:<br>
<input type="text" name="quantity">
<br><br>
<input type="button" value="Submit"
onclick="google.script.run
.withSuccessHandler(google.script.host.close)
.itemAdd(this.parentNode)" />
</form>
<!-- Addition #1 -->
<p>Status: </p><p id="status_value"></p>
</html>
问题:
上面的脚本在添加到#2时失败。似乎无法在html中找到id = status_value 元素。
注意:
我希望从.gs脚本文件中更新html,因为在某些情况下,该脚本可能需要一些时间,我想在脚本到达脚本中的某些里程碑时更改状态消息。
答案 0 :(得分:1)
“。gs”文件在服务器端运行,而html在客户端运行。您无法像将它们一起运行一样来回传递数据,因此,“ google.script.run” functionality。
如果要使用此功能从客户端调用功能后,再从服务器端脚本发送回数据,只需return
即可。
然后您可以使用返回的数据在客户端进行更改:
HTML
<input type="button" value="Submit" onclick="google.script.run .withSuccessHandler(function (data) {
document.getElementById("status_value").innerHTML = data;
google.script.host.close() ;
} ) .itemAdd()" />
.gs
function itemAdd(form) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
sheet.appendRow([" ", form.category, form.item, form.manupub, form.details, form.quantity]);
return "Submitted" ;
}
答案 1 :(得分:1)
请注意
...基于浏览器的功能(如DOM操作或Window API)不可用。
以上内容表示getElementById不能在服务器端代码(.gs)上使用。
来自 https://developers.google.com/apps-script/guides/services/#basic_javascript_features (2019年1月27日)
基本的JavaScript功能
Apps脚本基于JavaScript 1.6以及1.7的一些功能 和1.8。 因此,除了 内置和高级 Google服务:您可以使用
Array
之类的常见对象,Date
,RegExp
, 和 等等,还有Math
和Object
全局对象。但是,由于Apps脚本代码可以在Google的 服务器(不是客户端,除了HTML服务) 页),基于浏览器的功能(例如DOM操作或Window
API不可用。