简体   繁体   中英

socketio only works when using window.alert in function

I hit a very weird problem. I'm going into Webdev using flask and vanilla javascript. Now I'm trying to write a simple chat using socketio. It seems to only work when I use window.alert in the function. If I remove it the website just reloads. No output in terminal and no added element in the list. as soon as I put it back everything works fine, If I do. the message shows up in the list and in the terminal I can see the print of the flask app.

python/flask

import os
import requests

from flask import Flask, jsonify, render_template, request
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
socketio = SocketIO(app)

@app.route("/", methods=['GET', 'POST'])
def index():
    return render_template("index.html")


@socketio.on("submit")
def submit(text):
    print("SUBMIT:", text['text'])
    text = text['text']
    emit("announce text", {'text': text}, broadcast=True)

Javascript

document.addEventListener('DOMContentLoaded', () => {

      // Connect to websocket
      var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);

      // When connected, configure buttons
      socket.on('connect', () => {
          console.log("connected");

          document.querySelector('#form').onsubmit = () => {
              var text = document.querySelector('#text').value;
              // window.alert(text)
              socket.emit('submit', {'text': text});
              window.alert(text); // <-- This line makes it work and not work!
          };
      });

      socket.on('announce text', data => {
          // window.alert(data)
          var li = document.createElement('li');
          li.innerHTML = `${data.text}`;
          //window.alert(li);
          document.querySelector('#messages').append(li);
      });

HTML to have it all

<html>
      <head>
          <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
          <script src="/static/index.js"></script>
          <title>Vote</title>
      </head>
      <body>
          <ul id="messages">
          </ul>
          <hr>
          <form class="" id="form" action="" method="post">
              <input id="text" type="text" name="" value="">
              <input id="submit" type="submit" name="" value="Send">
          </form>
      </body>
  </html>

You need to preventDefault the submit event, because form is executing with default behavior - so it's making POST request to actual route (because action attribute is empty) - thats why page is reloading - and with preventDefault() you can stop form from doing this, just like that

document.querySelector('#form').onsubmit = (e) => {
  e.preventDefault();
  var text = document.querySelector('#text').value;
  socket.emit('submit', {'text': text});
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM