javascript - 无法从 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()
函数?
解决方案
使用如上所示的代码,我得到“内部比较”。数据是正确的值。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>
推荐阅读
- google-api - Dialogflow 获取实体
- timeout - 开始处理 HTTP 请求 POST 后 ASP.NET Core 3.1 错误超时
- android - 如何在无障碍服务中检测返回/主页新闻?
- typescript - 结合接口来生成一个新的类型,并结合它们的属性
- firebase - Firebase 动态链接和托管在同一(自定义)域上
- amazon-web-services - 通过 DynamoDB 建模帖子和主题
- string - 如何在 Haskell 中转换 Integer in String 和 String in Integer?
- javascript - 如何在 React Js 中添加 Firebase Firestore 文档自动生成的 ID 添加到集合中的自定义数据字段
- vue.js - 为什么我的 Vue 应用程序添加到 index.html 中的我的 favicon 引用?
- c - 在 C 中显示合同工时和加班时间