Home>

While watching dot_install, I exchanged code between client and server and wrote the code.
Somehow the server is standing, read the html file with localhost,
Even if you write text on the form, it has not been sent to the server.
Why?
And I'm using jquery on an html file and I want to know why

var app = require ("http"). createServer (handler),
    io = require ("socket.io"). listen (app),
    fs = require ("fs");
// Listen to server assembly with listen.
app.listen (3000);
console.log ("server start!");
function handler (req, res) {
  fs.readFile (__ dirname + "/ index.html", function (err, data) {
    if (err) {
      res.writeHead (500);
      return res.end ("Error");
    }
    res.writeHead (200);
    res.write (data);
    res.end ();
})
}
// Wait for client emit
io.sockets.on ("connection", function (socket) {
     socket.on ("emit_data", function (data) {
       console.log (data);
     });
});
Code
<! DOCTYPE html>
<html lang = "en">
  <head>
    <meta charset = "utf-8">
    <title>socket.io</title>
  </head>
  <body>
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <script src = "/ socket.io/socket.io.js"></script>
    <form name = "myid">
      <input type = "text" name = "msg">
      <input type = "submit" value = "submit">
      <script>
      function () {
        var socket = io.connect ();
        ("myid"). submit (function () {
        socket.emit ("emit_data", ("msg"). val ());
        });
      };
      </script>
  </body>
</html>
Code
  • Answer # 1

    There are a few points that I'm interested in.

    1 Double quotes on this line are full-width.
    <script src = "/ socket.io/socket.io.js"></script>
    Positive<script src ="/socket.io/socket.io.js"></script>

    2 When specifying an attribute value with the html tag, do not include spaces.
    <form name ="myid">
    Positive<form name ="myid">

    3 If you are using jQuery, specify the selector like this.

    $('form [name = "myid"]'). submit (function () {
        socket.emit ("emit_data", $('input [name = "msg"]'). val ());
    });

    4 Please rewrite the script tag like this. An anonymous function.

    (function () {
        var socket = io.connect ();
        $('form [name = "myid"]'). submit (function () {
            socket.emit ("emit_data", $('input [name = "msg"]'). val ());
        });
    }) ()

    Since I only listed the points I was interested in, there may be omissions, leaks, etc.
    If an error message is output on the browser console, add it to the question.

      

    I'm using jquery in an html file, but I want to know why

    Do you know what jQuery is in the first place?
    Find out what jQuery is and get as much information as you want.
    If the question means "What are the benefits of using jQuery in this program?", It is a completely different question from the title, so please post a new question.