【问题标题】:Google Apps Script return array values and use them in a javascript functionGoogle Apps 脚本返回数组值并在 javascript 函数中使用它们
【发布时间】:2015-06-14 14:13:06
【问题描述】:

我正在尝试返回一个数组并在 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 函数。我怎样才能做到这一点?

【问题讨论】:

  • 这是访问电子表格数据的另一种方式developers.google.com/apps-script/guides/html/…
  • Tnx 链接,但问题是 getValues() 在数组中返回一个数组。所以还是要循环遍历得到下面的结构:test1,test2。而不是,[test1],[test2]。因此,我需要返回一个数组

标签: javascript arrays google-apps-script


【解决方案1】:

您需要一个链接到您的google.script.runwithSuccessHandler() 方法:

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];
  }
};

【讨论】:

  • 有趣。 Tnx 为您的评论,它现在返回我的数组的内容!但是如何在另一个函数中使用var myTwoD_Array?因为我要返回的位置也需要在其他功能中使用。
  • 将数组放入浏览器window对象。请参阅更新的答案。您可以创建一个全局变量,或者创建一个全局对象,然后将数组放入全局对象中,但是将其放入 window 对象中是最简单、最直接的方法。
猜你喜欢
  • 2016-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-21
  • 2017-08-28
  • 1970-01-01
相关资源
最近更新 更多