html - 如何在 ejs 中每 2 秒更新一次时间元素
问题描述
我创建了一个 dashboard.js 文件和几个 .ejs 文件
这是我的 stats.ejs 文件
<tr>
<th scope="row" class="list-group-item d-flex justify-content-between align-items-center" data-toggle="tooltip" title="Duration"> Duration </th>
<td width="80%"><i class="fa fa-fw fa-music" aria-hidden="true"></i> <span class="col-5 text-nowrap" id="Duration"><% if(player) { %> <%= time %> <% } else { %>00:00 <% }%></span></td>
</tr>
我如何每 2 秒升级一次时间
这是在dashboard.js 文件中
app.get("/dashboard/:guildID/stats", checkAuth, (req, res) => {
const guild = client.guilds.get(req.params.guildID);
let player = client.music.players.get(req.params.guildID);
let time;
if (player) time = duration(player.queue[0].duration ).toString();
if (!guild) return res.status(404);
const isManaged = guild && !!guild.member(req.user.id) ? guild.member(req.user.id).permissions.has("MANAGE_GUILD") : false;
if (!isManaged && !req.session.isAdmin) res.redirect("/");
renderTemplate(res, req, "guild/stats.ejs", {guild , player ,time});
});
时间变量每秒更新一次,所以我能在这里做什么?
解决方案
实现这一目标的一种方法是使用前端 JavaScript 触发网络以获取最新信息
const yourInfoSegment = $('#segment');
// Fetching the latest data every 2 seconds
setInterval(async () => {
try {
const res = await fetch('YOU-API.com/dashboard/${guidID}/stats');
if(!res.ok) {
// Shows user there is a error while fetching data
return;
}
// Updating the DOM with the new HTML code from the API
const htmlCode = await res.text();
yourInfoSegment.innerHTML = htmlCode;
}
catch (err) {
// Show some error UI to the user
console.error(err);
}
}, 2 * 1000);
推荐阅读
- gps - 是否可以通过插补来近似缺失的位置数据?
- javascript - 怎么刮
- python-3.x - 如何在 Sanic 中获取推荐网站 url
- html - 显示:弯曲;不适用于
在 Safari 上 - python - 使用 yaml/oyaml 的类型转换问题
- drupal - 如何在 Drupal 8 中扩展给定查询以按英里搜索?
- jenkins - Jenkins Pipeline - Jenkins SCM 步骤。结帐返回不参考提供的参数的无效数据
- apache-spark - 如何计算包含相同值的间隔(行集)的开始/结束?
- c# - 在没有子数组 Linq 的情况下返回孩子和子孩子
- jaspersoft-studio - 了解项目组织和基本术语