google.script.run.withSuccessHandler 返回未定义。我该如何解决?

时间:2021-02-22 16:12:04

标签: google-apps-script google-sheets-api

我正在尝试获取电子表格的最后一行并将其放入侧边栏。这是我的代码:

code.gs

function onOpen(e) {
  SpreadsheetApp.getUi()
      .createMenu('Demo')
      .addItem('DemoChild', 'showSidebar')
      .addToUi();
}


function showSidebar(){
    var widget = HtmlService.createHtmlOutputFromFile('a.html');
    widget.setTitle('Demo');
    SpreadsheetApp.getUi().showSidebar(widget);
}

function getRowsUsed(sheetname){
  var sheet = SpreadsheetApp.getActiveSpreadsheet()
  var range = sheet.getSheetByName(sheetname)
  var rangeStartEnd = range.getLastRow()
    
  return rangeStartEnd;
};

a.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
    function getValue(a) {
      return a;
    }
    
    function doIt(){
      var res = google.script.run.withSuccessHandler(getValue).getRowsUsed('Sheet1');
      alert(res);
    }
    
    </script>
  </head>
  <body>
  <p>
    <script>doIt();</script>
  </p>
  </body>
</html>

它返回的不是数字,而是 undefined。我不知道我做错了什么。有人可以帮帮我吗?非常感谢。

1 个答案:

答案 0 :(得分:1)

google.script.run.withSuccessHandler(function)

  • 设置一个回调函数,如果服务器端函数成功返回则运行。服务器的返回值作为第一个参数传递给函数,用户对象(如果有)作为第二个参数传递。
  • 返回一个 google.script.run

您期望的值将传递给您指定的回调函数,即 getValue(a)。如果要查看getRowsUsed(sheetname)返回的值,可以在a函数中显示getValue(a)的值

示例代码:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
    function getValue(a) {
      var div = document.getElementById('output');
      div.innerHTML = 'Num of rows = '+ a;
    }
    
    function doIt(){
      google.script.run.withSuccessHandler(getValue).getRowsUsed('Sheet1');
      
    }
    
    </script>
  </head>
  <body>
    <div id="output"></div>
  <p>
    <script>doIt();</script>
  </p>
  </body>
</html>

输出:

enter image description here

相关问题