2015-06-14 51 views
1

我想要返回一個數組並在javascript函數中使用它,但它似乎不起作用。我Code.gs如下:谷歌應用程序腳本返回數組值,並在一個JavaScript函數中使用它們

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(); 
} 

所以我想在陣列,其內容爲Hello功能通過在我的測試html的。我該如何做這項工作?

+0

這是另一種方式來訪問電子表格數據https://developers.google.com/apps-script/guides/ html/templates#calling_apps_script_functions_from_a_template –

+0

Tnx的鏈接,但問題是,getValues()返回一個數組中的數組。所以仍然需要通過循環來獲得以下結構:test1,test2。而不是[test1],[test2]。因此,我需要返回一個數組 – user2237168

回答

2

你需要一個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]; 
    } 
}; 
+0

有趣。 Tnx爲您的評論,它現在返回我的數組的內容!但是如何在另一個函數中使用'var myTwoD_Array'?由於我要返回的地點也需要在其他功能中使用。 – user2237168

+0

將數組放入瀏覽器'窗口'對象中。查看更新的答案。您可以創建一個全局變量,或創建一個全局對象,然後將該數組放入全局對象中,但將其放入「窗口」對象中是最簡單和最直接的。 –

相關問題