tic*_*tic 5 google-apps-script
在Google Apps脚本中,我有以下脚本:
function doGet() {
return HtmlService.createHtmlOutputFromFile('mypage');
}
function writeSomething() {
return "<h1>hi people</h1>";
}
Run Code Online (Sandbox Code Playgroud)
和以下的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>
Run Code Online (Sandbox Code Playgroud)
当我点击"更新"链接时,div内容从"等待..."变为"未定义".我想google.script.run不能作为函数调用.那么,我该如何解决这个问题呢?(显然,这是一个玩具示例;我需要一种方法来更新脚本中的div内容,而不是来自html文件)
Cor*_*y G 17
函数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>
Run Code Online (Sandbox Code Playgroud)
或者等效地,您可以内联指定回调函数:
...
<script>
function go() {
google.script.run.withSuccessHandler(function(whatToWrite) {
document.getElementById("div").innerHTML=whatToWrite;
}).writeSomething();
}
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18452 次 |
| 最近记录: |