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

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

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

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

所以我想将数组及其内容传递给 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

};

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

JSON.stringify(yourArray);

您的数组名为 locations

return JSON.stringify(locations);

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

关于javascript - Google Apps 脚本返回数组值并在 javascript 函数中使用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30830392/

相关文章:

c - 在 C 中为数组的元素分配随机值

javascript - 在 HTML 中调用 Google Apps 脚本函数

google-apps-script - 使用 Google App Script HtmlService 提交表单

javascript - 使用 map/reduce 递归计算状态?

javascript - 在同一股票面板中显示不同的图表(amCharts)

javascript - 替换功能只能使用一次(javascript)

c# - 在 LINQ 中分组时如何显式声明类型?

java - 将 double 组转换为 double ArrayList

javascript - Google 图表(表格)不显示{来自另一张表格的查询}

javascript - 如何在 jquery 中向数组文本框添加值?