【发布时间】:2018-05-29 23:36:33
【问题描述】:
我正在尝试用脚本绑定到的电子表格中的数据填充我的 HTML 文件中的选择元素。
到目前为止,我有以下 newDeal.html 的代码。空的选择元素 (id="contactname") 是我需要用从 arr_customers() 函数返回的数据填充的元素:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body onload="onload()">
<p>Contact name:</p>
<select id="contactname" autocorrect="on" autocomplete="on">
</select>
</body>
<script>
var vals;
function placeCustomers(values) {
var select = document.getElementById("contactname");
for(var i = 0; i < values.length; i++) {
Logger.log(i);
var opt = values[i];
var el = document.createElement('option');
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
function onload() {
placeCustomers(vals);
}
function onSuccess(values) {
vals = values;
}
google.script.run.withSuccessHandler(onSuccess).arr_customers();
</script>
</html>
在服务器端,我有 arr_customers 函数,它返回从工作表“客户列表”中选择的项目。该函数在单独运行时工作正常,并返回一个带有名称的数组(如:['Bruno','Neymar']):
function arr_customers() {
var tbl = SpreadsheetApp.openById('my-spreadsheet-id').getSheetByName('Customers List').getDataRange().getValues();
var return_array = [];
for (var i = 1; i < tbl.length; i++) {
if (tbl[i][6] == 'C') { // condition needed for customer to go to list
return_array.push(tbl[i][1]);
}
}
return return_array;
}
最后,自定义菜单打开模态对话框的代码:
function uiBuilder() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Project')
.addItem('Create new project...', 'newProject')
.addToUi();
}
function newProject() {
var html = HtmlService.createHtmlOutputFromFile('newDeal');
SpreadsheetApp.getUi().showModalDialog(html, 'New Project');
}
问题是在 arr_customer 返回值后 onSuccess 函数没有运行。我使用了一些日志来发现这一点。我什至评论了所有不必要的代码,并尝试在 onSuccess 函数中使用一行“Logger.log('test')”通过Spreadhseets UI 运行它,但日志中没有任何显示。
有人知道为什么会这样吗?我看过谷歌文档,上面写着 withSuccessHandler:
设置一个回调函数在服务器端函数返回时运行 成功地。服务器的返回值被传递给函数 第一个参数,用户对象(如果有)作为第二个参数传递 论据。
也许我错过了什么,如果有人有任何线索,请分享:)
【问题讨论】:
-
google.script.run行应该何时执行?你没有它在一个函数中。 -
它在用户打开 HTML 时执行。我已经检查过了,弹出窗口时arr_customer函数成功运行。
-
另外一件事:我也试过用withFailureHandler,回调函数也没有到达
-
如文档中所述,
google.script.run异步任务的故障处理程序仅在服务器函数抛出未处理的异常时才被调用。如果服务器函数以任何其他方式退出,则其输出(来自return < something >,否则来自undefined)将传递给任务的成功处理程序。 PS 您编写的onSuccess函数只是在您的客户端代码中设置一个变量 - 它不会告诉您客户端代码中的任何其他函数对该变量的新值执行任何操作。 -
我明白你的意思。
arr_customers函数成功返回值,onSuccess函数没有运行(删除所有代码并使用 Log 检查)。关于您的 PS:onSuccess在变量上写入值,然后请注意<body>元素中的操作onload。它应该使用变量上的值运行函数placeCustomers。无论如何,在我的第一个代码中,我在onSuccess中调用了placeCustomers...这只是一个解决此问题的实验。
标签: google-apps-script google-sheets