javascript - 无法从 Google 脚本返回 2D 数组以在我的 HTML 中使用

标签 javascript html google-apps-script google-sheets

我正在尝试使用以下方法从 Google 电子表格返回二维数组:

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;
     }

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

    <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() 函数。我什至尝试在 Google 脚本文件中使用 JSON.stringify(data) 并返回一个字符串,然后在 HTML 脚本中使用 JSON.parse(data) 但仍然没有得到所需的结果。

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

最佳答案

使用上面所示的代码,我得到“内部比较”。并且数据是正确的值。 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>

关于javascript - 无法从 Google 脚本返回 2D 数组以在我的 HTML 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51885080/

相关文章:

javascript - 在 Javascript 中调用嵌套函数 - 在 jQuery.ajax.success 中调用时未定义错误

javascript - 如何在我的输入表单中阻止 html 和 url

javascript - Google 脚本查看文本是否包含值

google-apps-script - 找不到方法 getRange(number,number,number,(class))

javascript - Node.JS 中 child_process 的 execFile 中的异步函数

javascript - jQuery 正则表达式匹配帮助(可选条件)

html - 启用浏览器的表单自动填充

google-apps-script - 编辑库中 Google 脚本的早期版本

javascript - 为什么在 document.ready() 中声明的函数在调用时未定义?

javascript - 如何从 getCurrentPosition() 获取坐标