无法从前端获取值……“document.querySelector('#text').value;”不工作

can't fetch value from frontend… “document.querySelector('#text').value;” not working

html代码:

<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
        socket.on('connect', () => {
                const selection = document.querySelector('#text').value;
                socket.emit('submit value', {'selection':selection});
            });
        socket.on('submit text', data => {
            const li = document.createElement('li');
            li.innerHTML = `msg: ${data.selection}`;
            document.querySelector('#list').append(li);
        });
    });
</script>
<title>chat room</title>
</head>
<body>
    <h1 style="font-family:verdana; font-style:italic;">Chat room!!!</h1>
    <ul id="list">
    </ul>
    <hr>
    <form id="chat">
        <input id="text" autocomplete="off" autofocus placeholder="enter text">
        <input type="submit">
    </form>
</body>

python代码:

import os

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

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


@app.route("/")
def index():
    return render_template("index.html")

@socketio.on("submit value")
def chatting(data):
    selection=data["selection"]
    print(selection)
    emit("submit text", {"selection":selection}, broadcast=True)

大家好,我正在尝试为我的课程项目制作一个 'chat room',上面是我的代码。因此,当我提交表单时,什么也没有发生,我没有得到任何输出。看来我输入的文本没有发送到服务器。请帮我解决这个问题。谢谢。

您的 javascript 目前没有表单提交的处理程序。只需在 document.addEventListener:

中添加
$('form#chat').submit(function(event) {
    const selection = document.getElementById('text').value;
    socket.emit('submit value', {'selection':selection});
    return false;
});