use*_*168 2 javascript arrays google-apps-script
我正在尝试返回一个数组,并在javascript函数中使用它,但它似乎不起作用。我的Code.gs如下:
function doGet() {
return HtmlService.createHtmlOutputFromFile('test')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function test() {
var locations = [];
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/13q7pIeMUHll6_5xBUpBavaBqALt9fnFnOIO-Hwy_pFc/edit'),
sheet = ss.getActiveSheet(),
range = ss.getRange("D2:D4"),
values = range.getValues();
for (var r=1; r<values.length; r++) {
var row = values[r];
locations.push(row[0]);
}
return locations;
}
Run Code Online (Sandbox Code Playgroud)
我的test.html中的函数如下所示:
function hello() {
google.script.run.test();
}
Run Code Online (Sandbox Code Playgroud)
所以我想将数组及其内容传递给test.html中的hello函数。我该如何进行这项工作?
您需要一个withSuccessHandler()链接到您的方法google.script.run:
function hello() {
google.script.run
.withSuccessHandler(injectHTML)
.test();
}
//This captures the returned string from the server side code
function injectHTML(argReturnedArray) {
//To Do - code to inject the HTML
};
Run Code Online (Sandbox Code Playgroud)
不幸的是,服务器端.gs代码将仅返回字符串。但是有一种解决方法。使用:
JSON.stringify(yourArray);
Run Code Online (Sandbox Code Playgroud)
您的数组名为locations。
return JSON.stringify(locations);
Run Code Online (Sandbox Code Playgroud)
现在您需要将JSON字符串转换回数组:
function injectHTML(argReturnedArray) {
/* Put the array into the browsers window object in order to make the
* array named myReturnedArray available to all other functions.
*/
window.myReturnedArray = JSON.parse(argReturnedArray);
//To Do - code to inject the HTML
};
//Get the array in another function
function myOtherFunction() {
//Get the array from the browsers window object
var theArray = window.myReturnedArray;
var i=0, thisElement="";
for (i=0;i<theArray.length;i+=1) {
thisElement = theArray[i];
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9382 次 |
| 最近记录: |