1
サーバー時間ジェネレーターを備えた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
ページのコードは、私が4つの<span>
Sを埋め、その後、サーバーをポーリングしますページをレンダリングしたい
<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>
ですサーバーの応答値と比較します。
サーバーとクライアントを接続するルートが
app.get('/gettime', getTime.sendCurrentUTCTimeString);
app.get('/gtm', function(req, res, next) {
res.render('gettime', {});
});
すべてのサーバーは、すべての応答とともに「日付」ヘッダーを送信します。独自のメカニズムを使用する代わりに、そのヘッダー値を使用することをお勧めします。 – Tomalak
Expressアプリケーションでサーバーを定期的にポーリングするのは、Socket.ioを使用してクライアントに変更を簡単にプッシュすることができたときに、それを実行する奇妙な方法です。 –
合意。それにもかかわらず、これは私がこれを解決するために必要な方法でした。私は明日の解決策を掲載するだろう。 –