我正在写一个聊天应用程序。首先我通过Ajax加载了我的观点,但后来我意识到没有必要,因为我可以使用快速输出的导出。我认为这是一个更好的解决方案,但我现在不知道如何将一个变量从我的登录表单传递给script.js。将rooms.js中的用户名(username = req.body.user;
)传递给server.js是有效的,因为我在控制台中有一个正确的名称,我在文本输入中输入,但是当我向script.js发出'test'时什么都没发生,我的浏览器控制台里什么都没有。我认为控制台中的消息会显示片刻,然后加载新视图以使其消失。我试图改变代码的顺序,但没有帮助。任何sugestions?难道我做错了什么 ?我刚刚开始学习节点和表达,所以我将不胜感激任何帮助。
server.js
var express = require('express')
, routes = require('./routes')
, music = require('./routes/music')
, art = require('./routes/art')
, rooms = require('./routes/rooms')
, http = require('http')
, app = express()
, server = http.createServer(app)
, io = require('socket.io').listen(server)
, path = require('path')
, jade = require('jade')
, mysql = require('mysql');
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(app.router);
});
app.get('/', routes.index);
app.get('/music', music.rooms);
app.get('/art', art.rooms);
app.post('/rooms', rooms.rooms);
io.sockets.on('connection', function(socket) {
socket.on('joinRoom', function(data) {
socket.username = username;
socket.room = data.room;
console.log('socket room and username in console' + socket.room+socket.username);
socket.join(socket.room);
socket.emit('test');
});
server.listen(3000);
的script.js
var socket = io.connect();
$(document).ready(function() {
$('#rooms').on('click', 'a', function() {
var room = $(this).data('id');
socket.emit('joinRoom', {room: room});
});
socket.on('test', function(){
console.log('check if it works');
});
});
index.jade
include header.jade
div#page
div(class="box")
form(name="input", action='rooms', method="post")
div
p
| Login:
input(type="text", name="user", class="user")
input(type="submit",class="submit",value="Login")
rooms.jade
include header.jade
div#page
div(class="box")
div#rooms
h2 Rooms
a(data-name='abrakadabra', data-id='1', href='music') Abrakadabra
a(data-name='aloha', data-id='2', href='art') Aloha
路线文件夹中的rooms.js
exports.rooms = function(req, res){
res.render('rooms', { title: 'Rooms' });
username = req.body.user;
};
music.js(其中一个房间)
exports.rooms = function(req, res){
res.render('music', { title: 'Music room' });
};
答案 0 :(得分:0)
将event.preventDefault()添加到您的房间点击功能。这些链接正在刷新页面,它们不应该。
var socket = io.connect();
$(document).ready(function() {
$('#rooms').on('click', 'a', function() {
event.preventDefault();
var room = $(this).data('id');
socket.emit('joinRoom', {room: room});
});
socket.on('test', function(){
console.log('check if it works');
});
});