如何在NodeJS中用HTML语言显示实时变量 [英] how to display a realtime variable in nodejs in HTML

查看:24
本文介绍了如何在NodeJS中用HTML语言显示实时变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在NodeJS中使用setInterval()函数每隔‘x’秒更新几个变量(来自各种API的价格)

我希望在HTML中显示这些变量,并让它们每‘x’秒实时更新一次。

如何使用或不使用Socket.io

推荐答案

如果您不想使用socket.io,您可以使用AJAX调用,但我认为这是更痛苦的方式...

如果您使用socket.io,他们的GitHub上有很多很好的例子:Chat example

在您的节点JS中:

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>

我的代码不完整,但显示了需要了解的要点。

这篇关于如何在NodeJS中用HTML语言显示实时变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆