GAS:从电子表格数据中填充下拉列表

时间:2020-10-15 20:59:05

标签: javascript google-apps-script

我正在尝试根据Google Spreadsheet工作表中的信息填充Web应用程序中的下拉列表

这是我的代码:

从电子表格获取数据的函数:

function getBotIDDropDownArray(){
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName("(GetBots)");
  var wslr = ws.getLastRow();
  return ws.getRange(1, 2, wslr - 1, 1).getValues();
}

在我的网络应用程序的Javascript代码部分中,我具有以下内容:

首先,确保侧边栏加载:

document.addEventListener("DOMContentLoaded", afterSidebarLoads);

然后,调用将填充下拉列表的函数

function afterSidebarLoads(){
      google.script.run.withFailureHandler(function(e){console.log("failure handler",e)}).withSuccessHandler(afterBotIDDropDownArrayReturned).getBotIDDropDownArray();
}
//Validating afterBotIDDropDownArrayReturned

function afterBotIDDropDownArrayReturned(arrayOfArrays){
      var item = document.getElementById("bot-id");
      arrayOfArrays.forEach(function(r){
        var option = document.createElement("option");
        option.textContent = r[0];
        item.appendChild(option);
      });
 };

HTML代码:

<div class="form-group">
  <label for="bot-id">Bot ID</label>
    <select class="form-control" id="bot-id">
    </select>
</div>

第一期:

首先检查开发者控制台后,我注意到以下错误: enter image description here

根据这个问题: There was an error during the transport or processing of this request. Error code = 10, Path = /wardeninit

解决方案是在将BotIDDropDownArray返回为()之后封装我的函数,并按如下所示执行它:

(function afterBotIDDropDownArrayReturned(arrayOfArrays){
  var item = document.getElementById("bot-id");
  arrayOfArrays.forEach(function(r){
    var option = document.createElement("option");
    option.textContent = r[0];
    item.appendChild(option);
  });
})();

第二期:

但是,在上一次修复后,我得到此错误:

ArrayOfArrays未定义。

enter image description here

奇怪的是,因为getBotIDDropDownArray实际上是在捕获信息。

此外, withFailureHandler()在之前被调用过,但是没有任何说明。

1 个答案:

答案 0 :(得分:1)

我遵循了此步骤,以获取有关错误类型的更多信息。

Response and Error handling in Google Apps Scripts. doPost? withFailureHandler()?

更新的代码:

function afterSidebarLoads(){
  google.script.run.withFailureHandler(e => {
        console.error(e.message);
    }).withSuccessHandler(afterBotIDDropDownArrayReturned).getBotIDDropDownArray();
};

此后,我收到以下错误消息:

需要授权才能执行该操作

但是,我没有收到任何需要更新给定权限的通知。

反正解决了这个问题。

相关问题