无法从前端获取值..."document.querySelector('#text').value;" 不起作用



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)

大家好,我正在为我的课程项目创建一个"聊天室",上面是我的代码。所以当我提交表单时,什么也没发生,我没有得到任何输出。我输入的文本似乎没有进入服务器。请帮我解决这个问题。非常感谢。

您的javascript中目前没有表单提交的处理程序。只需将此添加到document.addEventListener:中即可

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

最新更新