表单提交后,socket.io聊天示例不起作用

我跟着从socket.io( http://socket.io/get-started/chat/ )的聊天教程,但一旦我来到的一部分,我必须从我被卡住的forms获取信息。

我从我的index.html文件得到的警告是:

 io is not defined please fix or add global io $ is not defined please fix or add global $ 

我试图添加网站链接到<script src="/socket.io/socket.io.js">但是这没有效果。 我使用c9.io作为我的开发工具。 使用node.js和socket.io。

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){ socket.on('chat message', function(msg){ io.emit('chat message', msg); }); }); http.listen(process.env.PORT, process.env.IP, function() { console.log("listening on *:" + process.env.PORT); }); 

的index.html

 <!-- I did not include the html and head tags in this example for readability purposes --> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> <script src="/socket.io/socket.io.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; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); </script> </body> 

添加事件窗口准备好

 var socket = io(); $(document).ready(function(){ $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); }); 
Interesting Posts