не могу получить значение из внешнего интерфейса… «document.querySelector ('# text'). value;» не работает - PullRequest
1 голос
/ 04 мая 2020

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)

это весь мой код. Когда я отправляю свою форму, ничего не происходит, я ничего не получаю. Кажется, мой введенный текст не go на сервер. Пожалуйста, помогите мне решить эту проблему. Спасибо.

1 Ответ

1 голос
/ 04 мая 2020

В данный момент у вас нет обработчика для отправки формы в javascript. Просто добавьте это внутрь document.addEventListener:

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