Google Apps Script 返回数组值并在 javascript 函数中使用它们

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30830392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:44:52  来源:igfitidea点击:

Google Apps Script return array values and use them in a javascript function

javascriptarraysgoogle-apps-script

提问by user2237168

I am trying return an array and use it in a javascript function, but it doesn't seem to work. My Code.gs is as follows:

我正在尝试返回一个数组并在 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;
}

The function in my test.html looks as follows:

我的 test.html 中的函数如下所示:

function hello() {
   google.script.run.test();
}

So I want to pass the array and its contents to the hello function in my test.html. How can I make this work?

所以我想将数组及其内容传递给 test.html 中的 hello 函数。我怎样才能使这项工作?

回答by Alan Wells

You need a withSuccessHandler()method chained to your google.script.run:

您需要一个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

};

Unfortunately, server side .gscode will only return a string. But there's a way to deal with that. Use:

不幸的是,服务器端.gs代码只会返回一个字符串。但是有一种方法可以解决这个问题。利用:

JSON.stringify(yourArray);

Your array is named locations.

您的数组名为locations.

return JSON.stringify(locations);

Now you need to convert the JSON string back to an array:

现在您需要将 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];
  }
};