Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

how to use google.script.run as if it was a function

In a Google Apps Script, I have the following script:

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

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

and the following html file:

<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>

When I click on the "update" link, the div content changes from "waiting..." to "undefined". I suppose that google.script.run cannot be called as a function. So, how can I solve this trouble? (obviously, this is a toy example; I need a way to update the div content from the script and not from the html file)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The function writeSomething() is run asynchronously so it happens but doesn't return the response as a local function would. (This is standard for JavaScript talking to a server). Instead, you need to specify a "callback" function which gets invoked when writeSomething() is finished.

Here's the corrected version of your 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>

Or equivalently, you can specify the callback function inline:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...