【问题标题】:socket.io chat example doesn't work after form submit表单提交后socket.io聊天示例不起作用
【发布时间】:2016-06-28 02:10:22
【问题描述】:

我按照 socket.io (http://socket.io/get-started/chat/) 的聊天教程进行操作,但是一旦我进入该部分,我就必须从表单中获取信息,我就卡住了。

我从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>

【问题讨论】:

  • 好像socket和jquery js都没有加载
  • 我意识到了这一点。我不知道为什么。据我所知,一切都已正确加载。
  • 你在哪里运行 nodejs?当地的?偏僻的?操作系统? Linux?检查防火墙了吗?
  • 在 c9 上。 cloud9 远程服务器/使用 nodejs

标签: javascript jquery node.js socket.io c9.io


【解决方案1】:

准备好添加事件窗口

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));
      });
});

【讨论】:

  • 似乎没有任何事情发生。
  • 请检查github.com/rauchg/chat-example并在您的项目中尝试,如果没有运行请纠正安装npm包
  • 该示例不起作用。我也收到与以前相同的警告。
  • 你有没有让它工作?我有同样的问题。
猜你喜欢
  • 2016-03-09
  • 1970-01-01
  • 2015-03-14
  • 2016-10-23
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
  • 2017-06-20
相关资源
最近更新 更多