gpt4 book ai didi

javascript - 使用 $.get 定期轮询 Express 服务器

转载 作者:太空宇宙 更新时间:2023-11-04 00:35:23 25 4
gpt4 key购买 nike

有一个带有服务器时间生成器的 Express 服务器。生成的时间发送到客户端页面gtm.hbs 。如何从客户端页面定期轮询服务器?我正在寻找 ajax 解决方案。

这是存储在 \routes\getTime.js 中的服务器端代码:

module.exports = {  
sendCurrentUTCTimeString: function(req, res, next) {
var currentUTCTime = new Date();
var currentUTCHours = currentUTCTime.getUTCHours();
var currentUTCMinutes = currentUTCTime.getUTCMinutes();
var currentUTCSeconds = currentUTCTime.getUTCSeconds();

currentUTCHours = ( currentUTCHours < 10 ? "0" : "" ) + currentUTCHours;
currentUTCMinutes = ( currentUTCMinutes < 10 ? "0" : "" ) + currentUTCMinutes;
currentUTCSeconds = ( currentUTCSeconds < 10 ? "0" : "" ) + currentUTCSeconds;
currentUTCHours = ( currentUTCHours == 24 ) ? "00" : currentUTCHours;

function pad(number, length) {
var str = "" + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}

var offset = new Date().getTimezoneOffset();
offset = ((offset < 0 ? '+' : '-') + pad(parseInt(Math.abs(offset / 60)), 2) + pad(Math.abs(offset % 60), 2));
offset = offset.match(/[\+-][0-9][0-9]/)[0];
res.send({currentUTCTime: currentUTCTime, currentUTCHours: currentUTCHours, currentUTCMinutes: currentUTCMinutes, currentUTCSeconds:currentUTCSeconds, offset: offset});
}
}

gettime.hbs页面代码为

<script>
$(document).ready(function() {
setInterval(function() {
var currentUTCHours;
var currentUTCMinutes;
var currentUTCSeconds;
var offset;
$.get('/gettime', function(data) {
debugger;
console.log(data);
currentUTCHours = data.currentUTCHours;
currentUTCMinutes = data.currentUTCSeconds;
currentUTCSeconds = data.currentUTCMinutes;
offset = data.offset;
$('#currentUTCHours').text(currentUTCHours);
$('#currentUTCMinutes').text(currentUTCMinutes);
$('#currentUTCSeconds').text(currentUTCSeconds);
$('#offset').text(offset);
});

console.log('currentUTCHours: ' + currentUTCHours);
}, 1500);
});
</script>

currentUTCHours: <span id="currentUTCHours"></span><br>
currentUTCMinutes: <span id="currentUTCMinutes"></span><br>
currentUTCSeconds: <span id="currentUTCSeconds"></span><br>
offset: <span id="offset"></span><br>

在这里,我想渲染一个页面,该页面将轮询服务器,然后填充四个 <span> s 与服务器响应值。

连接服务器和客户端的路由是

app.get('/gettime', getTime.sendCurrentUTCTimeString);
app.get('/gtm', function(req, res, next) {
res.render('gettime', {});
});

最佳答案

$('#currentUTCHours').text(currentUTCHours);
$('#currentUTCSeconds').text(currentUTCSeconds);

应位于 $.get() 内以使更改可见。

关于javascript - 使用 $.get 定期轮询 Express 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39270328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com