javascript - Javascript:意外
问题描述
我正在使用 Javascript 和 Flask 来制作“投票”系统。(使用socketio)
代码是:
application.py
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)
votes = {"yes": 0, "no": 0, "maybe": 0}
@app.route("/")
def index():
return render_template("index.html")
@socketio.on("submit vote")
def vote(data):
selection = data["selection"]
votes[selection] +=1
print(votes)
emit("announce vote", {"now": votes}, broadcast=True)
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script src="{{ url_for('static', filename='index.js') }}"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css">
<title>Vote</title>
</head>
<body>
<table class = "table" id="votes">
<tr>
<th scope = "col">#</th>
<th scope = "col">Number of votes</th>
</tr>
<tr>
<th scope = "col">Yes</th>
<td id = "votes-yes">0</td>
</tr>
<tr>
<th scope = "col">No</th>
<td id = "votes-no">0</td>
</tr>
<tr>
<th scope = "col">Maybe</th>
<td id = "votes-maybe">0</td>
</tr>
</table>
<hr>
<button class="btn btn-primary" type = "button" data-vote="yes">Yes</button>
<button class="btn btn-primary" type = "button" data-vote="no">No</button>
<button class="btn btn-primary" type = "button" data-vote="maybe">Maybe</button>
</body>
</html>
index.js
(静态)
document.addEventListener('DOMContentLoaded', () => {
// Connect to websocket
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
// When connected, configure buttons
socket.on('connect', () => {
// Each button should emit a "submit vote" event
document.querySelectorAll('button').forEach(button => {
button.onclick = () => {
const selection = button.dataset.vote;
socket.emit('submit vote', {'selection': selection});
};
});
});
socket.on('announce vote', data => {
var votes_now = data["now"];
document.querySelector('#votes-yes').innerHTML = votes_now[yes];
document.querySelector('#votes-no').innerHTML = votes_now[no];
document.querySelector('#votes-maybe').innerHTML = votes_now[maybe];
});
});
当我单击按钮时,它应该发出一个提交投票事件,然后将 1 添加到 Flask 系统中的字典,然后将消息广播回 Javascript,增加表中的值。
但是,在发出提交投票事件、向字典中加 1 并广播消息后,会<li>
出现一个带有“已记录投票:未定义”的标签。问题是什么?
解决方案
推荐阅读
- computer-science - 准备时间序列数据与机器学习的常规数据有什么区别
- sql - 如何只获取过去 30 天内未售出的商品?
- c# - 将项目推送到 MongoDb 中的深层嵌套数组
- java - 捕获运行时异常后程序执行停止
- java - 在 Java 中运行 Cucumber 时修改 CucumberOptions 标签
- excel - 在动态创建的数组中定位单个值
- flutter - 如何将每个项目从可观察到另一个来自异步函数的项目?
- asp.net - 使用 Google Drive API 在 .NET 中获取文档的修订历史
- sql-server - 气流 - 没有名为“airflow.contrib.operators.mssql_to_gcs”的模块
- javascript - 使用正则表达式在另一个子字符串中查找子字符串