如何使用google.script.run,就好像它是一个函数 [英] how to use google.script.run as if it was a function
问题描述
在Google Apps脚本中,我有以下脚本:
函数doGet(){
return HtmlService .createHtmlOutputFromFile( '我的空间');
}
函数writeSomething(){
return< h1> hi people< / h1>;
}
和以下html文件:
< html>
< a id =callerhref =#>更新< / a>
< br>
< div id =div>正在等待...< / div>
< script>
函数go(){
var a = google.script.run.writeSomething();
document.getElementById(div)。innerHTML = a;
}
document.getElementById('caller')。onclick = go;
< / script>
< / html>
当我点击更新链接时,div内容从waiting ...到未定义。我想google.script.run不能作为函数调用。
那么,我该如何解决这个问题呢? (很明显,这是一个玩具的例子;我需要一种方法来更新脚本中的div内容,而不是从html文件中更新)
函数writeSomething()是异步运行的,所以它会发生,但不会像本地函数那样返回响应。 (这是JavaScript与服务器通话的标准)。相反,你需要指定一个回调函数,它在writeSomething()完成时被调用。
以下是HTML的更正版本:
< html> ;
< a id =callerhref =#>更新< / a>
< br>
< div id =div>正在等待...< / div>
< script>
函数回调(whatToWrite){
document.getElementById(div)。innerHTML = whatToWrite;
}
函数go(){
google.script.run.withSuccessHandler(callback).writeSomething();
}
document.getElementById('caller')。onclick = go;
< / script>
< / html>
或者等价地,您可以内联指定回调函数:
...
< script>
函数go(){
google.script.run.withSuccessHandler(function(whatToWrite){
document.getElementById(div)。innerHTML = whatToWrite;
})。写一些东西();
}
...
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)
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();
}
...
这篇关于如何使用google.script.run,就好像它是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!