HTML 如何在 nodejs 中显示实时变量
how to display a realtime variable in nodejs in HTML
我正在使用 setInterval() 函数在 NodeJS
中每 'x' 秒更新一些变量(来自各种 API 的价格)
我想在 HTML 中显示这些变量,并让它们每 'x' 秒实时更新一次。
如何使用 Socket.io 或不使用它来解决这个问题
尝试模板化和模板引擎。
模板引擎是使您能够将变量传递给模板的东西。这些引擎呈现模板文件,其中包含您以 HTML 页面形式提供的数据。
我建议您尝试 'ejs',因为它非常接近 HTML 文件。 ejs 模板只是简单的 HTML 语法,带有 placefolder 供您传递数据。
但这需要您定期刷新页面。所以你可以试试 'AJAX' 让你刷新页面的一部分,同时从服务器发送和接收数据
如果你不想使用socket.io
,你可以使用AJAX
调用,但我认为这是更痛苦的方式...
如果你使用 socket.io
,他们的 GitHub 上有很好的例子:Chat example.
在你的 NodeJS 中:
var io = require('socket.io')(8080); // The port should be different of your HTTP server.
io.on('connection', function (socket) { // Notify for a new connection and pass the socket as parameter.
console.log('new connection');
var incremental = 0;
setInterval(function () {
console.log('emit new value', incremental);
socket.emit('update-value', incremental); // Emit on the opened socket.
incremental++;
}, 1000);
});
此代码应在您的应用程序中启动。
在您看来:
<html>
<body>
<pre id="incremental"></pre>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var socket = io('http://localhost:8080'); // Connect the socket on the port defined before.
socket.on('update-value', function (value) { // When a 'update-value' event is received, execute the following code.
console.log('received new value', value);
$('#incremental').html(value);
});
</script>
</body>
</html>
我的代码不完整,但显示了必须了解的内容。
我正在使用 setInterval() 函数在 NodeJS
中每 'x' 秒更新一些变量(来自各种 API 的价格)我想在 HTML 中显示这些变量,并让它们每 'x' 秒实时更新一次。
如何使用 Socket.io 或不使用它来解决这个问题
尝试模板化和模板引擎。 模板引擎是使您能够将变量传递给模板的东西。这些引擎呈现模板文件,其中包含您以 HTML 页面形式提供的数据。
我建议您尝试 'ejs',因为它非常接近 HTML 文件。 ejs 模板只是简单的 HTML 语法,带有 placefolder 供您传递数据。
但这需要您定期刷新页面。所以你可以试试 'AJAX' 让你刷新页面的一部分,同时从服务器发送和接收数据
如果你不想使用socket.io
,你可以使用AJAX
调用,但我认为这是更痛苦的方式...
如果你使用 socket.io
,他们的 GitHub 上有很好的例子:Chat example.
在你的 NodeJS 中:
var io = require('socket.io')(8080); // The port should be different of your HTTP server.
io.on('connection', function (socket) { // Notify for a new connection and pass the socket as parameter.
console.log('new connection');
var incremental = 0;
setInterval(function () {
console.log('emit new value', incremental);
socket.emit('update-value', incremental); // Emit on the opened socket.
incremental++;
}, 1000);
});
此代码应在您的应用程序中启动。
在您看来:
<html>
<body>
<pre id="incremental"></pre>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var socket = io('http://localhost:8080'); // Connect the socket on the port defined before.
socket.on('update-value', function (value) { // When a 'update-value' event is received, execute the following code.
console.log('received new value', value);
$('#incremental').html(value);
});
</script>
</body>
</html>
我的代码不完整,但显示了必须了解的内容。