[英]How to get data from Google Spreadsheet to HTML as a javascript variable?
I am trying to create webapp with html service.我正在尝试使用 html 服务创建 webapp。 Here is my code.
这是我的代码。
The code in code.gs
file. code.gs
文件中的代码。
function doGet() {
return HtmlService
.createTemplateFromFile('userendhtml')
.evaluate();
}
function getData() {
var sss = SpreadsheetApp.openById('xxxx');
var rawData = sss.getDataRange().getValues()
var data = []
for (var i = 0; i< rawData.length; i++){
data.push(rawData[i])
}
return data
}
Now I want to access this data as javascript variable for further processing (for creating table with querying).现在我想将此数据作为 javascript 变量访问以进行进一步处理(用于通过查询创建表)。 The code in
userendhtml.html
is userendhtml.html
中的代码是
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
var data2 = getData();
</script>
</body>
</html>
This doesn't store data to variable data2
.这不会将数据存储到变量
data2
。 So how to get data from spreadsheet in variable in javascript?那么如何从javascript变量中的电子表格中获取数据呢?
You want to use google.script.run
in conjunction with withSuccessHandler(...)
您想将
google.script.run
与withSuccessHandler(...)
结合使用
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
var data2;
google.script.run.withSuccessHandler(function(ret){
data2 = ret;
}).getData();
</script>
</body>
</html>
You could use the techniques found in the Templated Html reference that I gave you.您可以使用我提供给您的模板化 Html 参考中的技术。 But you could also do this:
但你也可以这样做:
<script>
var data2;
window.onload=function(){
google.script.run
.withSuccessHandler(function(dt){
data2=dt;
document.getElementById('myDiv').innerHTML=data2;
.getData();
}
</script>
The templated html approach loads on the server and this approach loads after the dom loads.模板化的 html 方法在服务器上加载,该方法在 dom 加载后加载。
I just tested this example as a dialog我刚刚将这个例子作为一个对话框进行了测试
function dialogTest() {
var html='<div id="mydiv"></div>';
html+='<script>var data2;window.onload=function(){google.script.run.withSuccessHandler(function(dt){data2=dt;document.getElementById("mydiv").innerHTML=data2;}).getMtData();}</script>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), 'Dialog Test');
}
function getMtData() {
return 'Hello World';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.