【问题标题】:Node.js with socket.io, capturing form data to display on pageNode.js 与 socket.io,捕获表单数据以显示在页面上
【发布时间】:2015-07-16 10:59:32
【问题描述】:

我正在尝试做的是基本操作,但无法将我的数据返回到页面。我想在将用户定向到聊天屏幕之前在表单中捕获一些用户信息,一旦定向到聊天屏幕,我将使用表单数据将他们的姓名和问题(来自表单)附加到聊天窗口。

我已经编辑了原始帖子,如果我将 index.js 中的行返回数据更改为:*

io.emit('user capture', data)

*...并注释掉聊天窗口中的显示无。

我将数据发布到聊天窗口,现在我只需要能够隐藏聊天窗口...有什么想法吗?

下面是我的 index.html:

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form[name="chat"] { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form[name="chat"] input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form[name="chat"] button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
      /*.chat { display: none; }*/
    </style>
  </head>
  <body>
    <div class="pages">
      <div class="user_capture">
        <form name="user_capture" enctype='application/json'>
          <button>Close</button><br/><br/>
          <label for="username">Your Name: *</label><br/>
          <input id="username" type="text" value="" name="username" autocomplete="off" required="required" /><br/>
          <label for="email">Email: *</label><br/>
          <input id="email" value="" name="email_address" autocomplete="off" /><br/>
          <label for="phone">Phone:</label><br/>
          <input id="phone" value="" name="phone" autocomplete="off" /><br/>
          <label for="question">Question: </label><br/>
          <textarea id="question" name="question">
          </textarea required="required"><br/><br/>
          <button>Chat</button>
        </form>
      </div>
      <div class="chat">
        <ul id="messages"></ul>
        <form name="chat">
          <input id="message" autocomplete="off" /><button>Send</button>
        </form>
      </div>
    </div>
    <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[name="user_capture"]').submit(function(){
        var data = {
          username:$('[name="username"]').val(),
          question:$('[name="question"]').val()
        }
        socket.emit('user capture', data);
        //return false;
      });

      socket.on('user capture', function(data){
        $('form[name="user_capture"]').hide();
        $('form[name="chat"]').show();
        // $('#messages').append(data.username +' says: '+ data.question);
      });


      $('form[name="chat"]').submit(function(){
        socket.emit('chat message', $('#message').val());
        $('#message').val('');
        return false;
      });

      socket.on('chat message', function(msg){
        $('#messages').append($('<li>').text(msg));
      });
    </script>
  </body>
</html>

下面是我的 index.js:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var status = 'Disconnected';

app.get('', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
    var status = 'Connected';
    socket.on('chat message', function(msg){
        io.emit('chat message', msg);
        io.emit('status', status);
    });
    socket.on('user capture', function(data){
        io.emit('user capture', data);
    });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

【问题讨论】:

    标签: node.js forms post socket.io


    【解决方案1】:

    使用下面的代码

     $('form[name="user_capture"]').click(function(e){
            e.preventDefault();
            var data = {
              username:$('[name="username"]').val(),
              question:$('[name="question"]').val()
            }
    

    【讨论】:

    • 将提交更改为单击并没有改变任何内容,将消息发布到聊天区域的功能也正在运行,并且也使用了提交。 PS我在提交user_capture表单后隐藏表单并显示聊天......这真的让我感到困惑!
    【解决方案2】:

    所以你们是对的,表单提交刷新页面并导致数据丢失我也决定根本不使用表单。只是输入和标签,因为我不使用 PHP,所以不需要 POST。以下是我的工作代码:

    index.html

    <!doctype html>
    <html>
      <head>
        <title>Socket.IO chat</title>
        <style>
          * { box-sizing: border-box; }
          body { margin: 0; padding: 0; font: 13px Helvetica, Arial; }
          [data-close] { float: right; }
          [data-status] { width: 100%; }
          .chat { display: none; }
          .chat .send-area { background: #000; padding: 15px; position: fixed; bottom: 0; width: 100%; }
          .chat .send-arae input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
          .chat [data-send] { float: right; text-align: center;width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
          .chat .send-area #message { width: 90%; padding: 9px; }
          #messages { width: 70%;float: left; list-style-type: none; margin: 0; padding: 0; }
          #messages li { padding: 5px 10px; }
          #messages li:nth-child(odd) { background: #eee; }
          [data-online] { float: right; background: #d9d9d9; width: 30%; }
          .clr { clear: both; }
        </style>
      </head>
      <body>
        <div class="pages">
          <a href="#" data-close>Close</a>
          <div class="user_capture">
              <label for="username">Your Name: *</label><br/>
              <input id="username" type="text" value="" name="username" /><br/>
              <label for="email">Email: *</label><br/>
              <input id="email" value="" name="email_address" /><br/>
              <label for="phone">Phone:</label><br/>
              <input id="phone" value="" name="phone" /><br/>
              <label for="question">Question: </label><br/>
              <textarea id="question" name="question">
              </textarea><br/><br/>
              <a href="#" data-user-capture>Chat</a>
          </div>
          <div class="chat">
            <div data-status></div>
            <ul id="messages"></ul>
            <ul data-online>
            </ul>
            <div class="clr"></div>
              <div class="send-area">
                <input id="message" autocomplete="off" /><a href="" data-send>Send</a>
              </div>
          </div>
        </div>
        <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>
          $(document).ready(function(){
    
            var socket = io.connect();
            var $close = $('[data-close]');
    
            $close.unbind().bind('click', function(){
              if(window.confirm("Are you sure?")) {
                location.reload();
              }
            });
    
            //CAPTURE
            $('[data-user-capture]').unbind().bind('click', function(e){
              e.preventDefault();
              //hide form show chat window
              $('.user_capture').hide();
              $('.chat').show();
    
              var data = {
                username:$('[name="username"]').val(),
                question:$('[name="question"]').val(),
              }
              socket.emit('user capture', data);
            });
            socket.on('user capture', function(data){
              $('#messages').append('<li><strong>'+data.username +' says: </strong>'+data.question+'<li>');
              console.log(JSON.stringify(data));
              $('[data-status]').append('<strong>Status: </strong>'+data.status);
              //$('[data-online]').each(data.online_users).append('<li>'+online+'</li>')
            });
    
            //SEND MESSAGE
            $('[data-send]').unbind().bind('click', function(e){
              e.preventDefault();
              if(!$('#message').val()){
                $('#message').focus();
                $('#message').attr('placeholder', 'Please enter a message...');
              } else {
                socket.emit('send', $('#message').val());
                $('#message').val('');
                // return false;
              }
            });
    
            socket.on('send', function(data){
              $('#messages').append('<li><strong>'+data.username +' says: </strong>'+data.msg+'<li>');
            });
          });
        </script>
      </body>
    </html>
    

    index.js

    var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io').listen(http);
    var username;
    var online_users = [];
    var status = 'Disconnected';
    
    app.get('', function(req, res){
      res.sendFile(__dirname + '/index.html');
    });
    
    io.on('connection', function(socket){
      socket.on('user capture', function(data){
        socket.username = data.username;
        data.online_users.push(socket.username);
        data.status = 'Connected';
        io.emit('user capture', data);
        console.log(data);
      });
        socket.on('send', function(msg){
        sendData = {
          msg:msg,
          username:socket.username
        };
        io.sockets.emit('send', sendData);
      });
    });
    
    http.listen(3000, function(){
      console.log('listening on *:3000');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-15
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      • 2019-04-14
      相关资源
      最近更新 更多