node.js - 如何进行简单的实时页面更新? [英] node.js - how to make a simple live page update?

查看:131
本文介绍了node.js - 如何进行简单的实时页面更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对node.js非常陌生,但实际上我只想通过学习语言来实现一件简单的事情。

I'm very very new to node.js, but there's actually only one simple thing that I am trying to achieve by learning the language.

我是喜欢创建一个网页,其中特定div中的代码可以即时热切换到当前查看该页面的用户。 (即div包含一些文本,但随后图像会替换它。)
理想情况下,交换将由网页管理员通过单击按钮手动执行,或者某些代码在服务器上触发或一些东西。网页的常规查看者无法执行此操作 - 他们只能看到页面上的实时更改。

I'd like to create a webpage, where by the code in a specific "div" can be hotswapped on the fly to users currently looking at that page. (ie. the div contains some text, but then an image replaces it.) Ideally, the swap would be executed manually by the the webpage's admin through the click of a button, or some code fired off on the server or something. Regular viewers to the webpage would not be able to do this - they only see the live changes on the page.

现实生活中的例子:

现场互联网广播是无线播放,因此div包含广播文字。
直播热线代码发生在广播播出时,网页的观众现在看到div中的html5广播播放器。

live internet broadcast is off-air, therefore the "div" contains "off-air" text. live hotswap of code happens when broadcast goes on-air, and the viewers of the webpage now see the html5 broadcast player in the "div" instead.

对于node.js新手来说,最简单的方法是什么?

What's the simplest way to go about doing this for a node.js newbie?

非常感谢:)

推荐答案

看看Socket.IO http://socket.io/#how-to -use

Take a look at Socket.IO http://socket.io/#how-to-use

当服务器决定广播变更用途时:

when the server decides to broadcast a change use:

io.sockets.emit('update-msg',{data:'this is the data'});

on the客户端首先连接socket.io,然后等待update-msg事件并更新你的dom:

on the client first connect socket.io and then wait for the "update-msg" event and update your dom:

var socket = io.connect('http://localhost');
socket.on('update-msg', function (msg) {
    console.log(msg);
    $('#mydiv').html(msg.data)
});

这篇关于node.js - 如何进行简单的实时页面更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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