2012-07-14 27 views
3

在谷歌Apps腳本,我有以下腳本:如何使用google.script.run,如果它是一個功能

function doGet() { 
    return HtmlService.createHtmlOutputFromFile('mypage'); 
} 

function writeSomething() { 
    return "<h1>hi people</h1>"; 
} 

和下面的HTML文件:

<html> 
    <a id="caller" href="#">update</a> 
    <br> 
    <div id="div">waiting...</div> 
<script> 
function go() { 
    var a=google.script.run.writeSomething(); 
    document.getElementById("div").innerHTML=a; 
} 
document.getElementById('caller').onclick = go; 
</script> 
</html> 

當我點擊「更新」鏈接,div內容從「正在等待」變爲「未定義」。我想google.script.run不能作爲函數調用。 那麼,我該如何解決這個麻煩? (顯然,這是一個玩具的例子;我需要一種方法來更新腳本中的div內容,而不是HTML文件)

回答

13

函數writeSomething()異步運行,所以發生但不返回響應作爲一個地方功能會。 (這是JavaScript與服務器通話的標準)。相反,你需要指定一個「回調」函數,它在writeSomething()完成時被調用。

這裏是你的HTML修正版本:

<html> 
    <a id="caller" href="#">update</a> 
    <br> 
    <div id="div">waiting...</div> 
<script> 
function callback(whatToWrite) { 
    document.getElementById("div").innerHTML=whatToWrite; 
} 
function go() { 
    google.script.run.withSuccessHandler(callback).writeSomething(); 
} 
document.getElementById('caller').onclick = go; 
</script> 
</html> 

或者等價地,你可以指定回調函數內聯:

... 
<script>  
function go() { 
    google.script.run.withSuccessHandler(function(whatToWrite) { 
    document.getElementById("div").innerHTML=whatToWrite; 
    }).writeSomething(); 
} 
... 
+0

因此,如何將它的工作,如果「

喜人們

」竟是一個交互式的jquery元素(你可以選擇),你想要將選擇的索引返回到google apps腳本中?任何想法如何做到這一點?或者換句話說:如何將「

hi people

」返回到google apps腳本,以便您可以在該環境中進一步編輯它? – 2014-03-17 03:34:52

相關問題