Jquery Socket.io-无法将消息从客户端发送到服务器端
我有两个档案-Jquery Socket.io-无法将消息从客户端发送到服务器端,jquery,node.js,sockets,express,socket.io,Jquery,Node.js,Sockets,Express,Socket.io,我有两个档案- index.html index.js 在index.html中,我有一个文本框。我想在控制台(node.js的命令提示符)上显示文本框中键入的消息 在index.html中,我写了以下内容- <script> var socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); re
- index.html
- index.js
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script>
但是,该消息没有显示在控制台中。我的代码有什么问题?
如果需要,请参考以下文件
index.js
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){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('chat message', function(msg){ //here is the listener to the event
console.log('message: ' + msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
index.html
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
//some code
</style>
</head>
<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();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
Socket.IO聊天
//一些代码
var socket=io();
$('form')。提交(函数(){
emit('chat message',$('#m').val());
$('m').val('');
返回false;
});
发送
在关闭
标记之前移动html文件中包含socket.io代码的块,以便仅在正文完成加载后加载脚本。您看到控制台上打印的内容吗?您正在查看哪个控制台,浏览器控制台或命令行控制台?尝试将html文件中包含socket.io代码的
块移动到关闭
标记之前。@BidhanA完美!谢谢你,比丹,成功了。我想在脚本加载的时候主体还没有加载。正如你所建议的,在工作结束后移动它。谢谢请写同样的答案,这样我就可以接受了!:)
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
//some code
</style>
</head>
<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();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>