pot*_*Art 9 google-sheets google-apps-script google-apps-script-web-application
我希望能够不断(实时)更新我的网络应用程序,这样,只要我的Google表格上有更新(通过使用应用程序脚本doGet功能配置的Webhook ),我构建的HTML仪表板中就会显示相同的内容。
我不需要设置工作表,webhook或HTML仪表板的帮助-我已经完成了所有设置。
我确实需要帮助/建议,无论何时我的功能或工作表上有更新(该部分并不重要),如何更新我的HTML仪表板(Web应用程序doGet)。
最好的例子是每次有新用户登陆您的网站时Google Analytics(分析)实时仪表板的更改方式。
PS。我知道我应该共享一些代码,但是我所拥有的一切都与我的实际需求无关。希望很清楚,但是如果您有需要看到我的代码/工作表的话,我很乐意创建一个虚拟版本。
您需要使用:
google.script.run.withSuccessHandler这是一个JavaScript异步客户端API,可让您与服务器端功能进行交互(可以在此处找到参考)。setInterval 函数以您认为合适的频率调用上述客户端API
这几乎是在脚本的code.gs部分中编写的代码。所有功能都驻留在其中的位置,这些功能可能与电子表格交互或充当Webhook
这是从* .html文件运行的代码,并在加载后在Web浏览器上运行。这是您使用“异步” API的地方
在我的虚拟设置中,我-
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Index').setTitle('Realtime Data');
}
function randomQuotes() {
var baseURL = 'https://thesimpsonsquoteapi.glitch.me/quotes';
var quotesData = UrlFetchApp.fetch(baseURL, { muteHttpExceptions: true });
var quote;
var imageURL;
if (quotesData.getResponseCode() == 200 || quotesData.getResponseCode() == 201) {
var response = quotesData.getContentText();
var data = JSON.parse(response)[0];
quote = data["quote"];
imageURL = data["image"];
} else {
quote = 'Random Quote Generator is broken!';
imageURL = 'https://cdn.shopify.com/s/files/1/1061/1924/products/Sad_Face_Emoji_large.png?v=1480481055';
}
var randomQuote = {
"quote": quote,
"imageTag": '<img class="responsive-img" src="' + imageURL + '">'
}
return randomQuote;
}
function getTime() {
var now = new Date();
return now;
}
Run Code Online (Sandbox Code Playgroud)
我只强调代码的相关方面
以下代码每10秒(10000 ms)获取一次随机报价
<script>
function onSuccess1(quotedata) {
var quoteactual = document.getElementById('quote');
quoteactual.innerhtml = quotedata.quote;
var quoteimg = document.getElementById('quoteImage');
quoteimg.innerhtml = quotedata.imagetag;
}
setInterval(function() {
console.log("getting quote...")
google.script.run.withSuccessHandler(onsuccess1).randomQuotes();
}, 10000);
</script>
Run Code Online (Sandbox Code Playgroud)
每1秒(1000 ms)提取一次时间
<script>
function onSuccess2(now) {
var div = document.getElementById('time');
var today = new Date();
var time = today.getHours() + " : " + today.getMinutes() + " : " + today.getSeconds();
div.innerhtml = time;
}
setInterval(function() {
console.log("getting time...")
google.script.run.withSuccessHandler(onsuccess2).getTime();
}, 1000);
</script>
Run Code Online (Sandbox Code Playgroud)
您可以访问整个脚本我的github仓库或使从原始脚本的副本。
这里的图像应该每10秒更改一次,计时器每1秒更改一次
可以在这里查看浏览器控制台日志-
我几周前写了这篇文章,概述了到目前为止每个人都在回答/评论的大部分内容,但是我希望我的解释也能有所帮助。
| 归档时间: |
|
| 查看次数: |
154 次 |
| 最近记录: |