首页 > 解决方案 > 无法从 Google 脚本返回二维数组以在我的 HTML 中使用

问题描述

我正在尝试使用以下方法从谷歌电子表格中返回一个二维数组:

function getData(){
      //this function reads data from the sheet and retuns a 2D array
          var spreadsheetID = //spreadsheet ID;
          var range = 'SchoolData!A2:B';
          var data = 
          SpreadsheetApp.openById(spreadsheetID).getRange(range).getValues();
          return data;
     }

返回的数据应compareID()在提交我的 HTML 表单后在函数中处理。

    <input type="submit" value="Submit" onclick= "authorise()">


    function authorise(){
        alert("inside authorise");
        google.script.run
        .withFailureHandler(errMsg)
        .withSuccessHandler(compareID)
        .getData();

    }

    function compareID(data){
        alert("inside compare");
        //process the data
    }


    function errMsg(){
        alert("no data was returned ");
    }

我的代码似乎总是去errMsg()并且从不进入compareID()函数。我什至尝试JSON.stringify(data)在 Google 脚本文件中使用并在 HTML 脚本中返回一个字符串JSON.parse(data),但仍然没有得到所需的结果。

我应该怎么做才能让我的代码进入compareID()函数?

标签: javascripthtmlgoogle-apps-scriptgoogle-sheets

解决方案


使用如上所示的代码,我得到“内部比较”。数据是正确的值。errMsg 是否在您的 html 中的其他任何地方调用?

function test() {
  try {
    var htmlTemplate = HtmlService.createTemplateFromFile('HTML_Test');
    var htmlOutput = htmlTemplate.evaluate();
    SpreadsheetApp.getUi().showModalDialog(htmlOutput, "Sample");
  }
  catch(err) {
    Logger.log(err);
  }
}

function getData(){
  //this function reads data from the sheet and retuns a 2D array
  var spreadsheetID = SpreadsheetApp.getActiveSpreadsheet().getId();
  var range = 'Sheet2!A2:B';
  var data = SpreadsheetApp.openById(spreadsheetID).getRange(range).getValues();
  return data;
}

<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div>
  <input type="submit" value="Submit" onclick= "authorise()">
</div>
<script>
  function authorise(){
    alert("inside authorise");
    google.script.run
    .withFailureHandler(errMsg)
    .withSuccessHandler(compareID)
    .getData();
  }

  function compareID(data){
    alert("inside compare");
    //process the data
  }

  function errMsg(){
    alert("no data was returned ");
  }
</script>
</body>
</html>

推荐阅读