我的应用程序有2个部分,注册表和索引/登录,情况是我想在每次用户注册时更新,这样做的困难部分是使索引显示查询来自开始,而不是由寄存器发送。代码:
索引脚本:
<script>
var socket = io();
socket.on('registered', function (msg) {
$('#messages').empty().append(msg).hide().fadeIn(500);
console.log(msg);
});
function message() {
var mes = document.getElementById('text').value;
console.log(mes);
socket.emit('registered', mes);
}
</script>
获取用户的索引代码:
global.mysql.query("SELECT * FROM users ORDER BY id DESC LIMIT 4", function (err, rows, fields) {
if (err) throw err;
var msg = "";
for(var i = 0; i <= rows.length-1; i++) {
msg += rows[i].username + '<br>';
}
global.io.sockets.emit('registered', msg);
})
注册码:
router.post('/register', function(req, res, next) {
global.mysql.query("INSERT INTO users (id, username) VALUES (?,?)", [null, req.body.user], function () {
global.mysql.query("SELECT * FROM users ORDER BY id DESC LIMIT 4", function(err, rows, fields) {
if (err) throw err;
var msg = "";
for(var i = 0; i <= rows.length-1; i++) {
msg += rows[i].username + '<br>';
}
global.io.sockets.emit('registered', msg);
})
});
});
我不知道为什么,因为它是相同的代码...
答案 0 :(得分:0)
我修复了它将io.on放入路由器:
router.get('/', function(req, res, next) {
res.sendFile(global.path + '/views/index.html');
global.mysql.query("SELECT * FROM users ORDER BY id DESC LIMIT 4", function (err, rows, fields) {
if (err) throw err;
var msg = "";
for(var i = 0; i <= rows.length-1; i++) {
msg += rows[i].username + '<br>';
}
global.io.on('connection', function(socket){
console.log('a user connected');
global.io.sockets.emit('registered', msg);
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
})
});
希望它可以帮助任何人!