var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
for(i=0; i<10; i++){
io.emit('notification', i);
}
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
<body>
<style type="text/css">
.chatting {
width: 40px;
height: 40px;
border-radius: 50%;
margin-left: auto;
margin-right: auto;
background-color: #a6a6a6;
}
</style>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
socket.on('notification', function(msg){
alert(msg);
});
</script>
<div class = chatting></div>
</body>
当服务器推送某些值时,我只是尝试将数据追加到客户端的div中。怎么做。这是我的代码。警报运行正常。但我需要将数字插入到div中。每次服务器推送时,该号码应自动更改,例如Facebook上的通知。
谢谢。
最佳答案
<script>
var socket = io();
function appendNotification(notification){
document.getElementById("notifications").innerHTML = "<div>" + notification + "</div>";
}
socket.on('notification', function(msg){
appendNotification(msg);
});
</script>
ADD the id to your html
<div class="chatting" id="notifications"></div>