Flask实现按钮无刷新动态增减BPM值问题求助
Flask实现无刷新BPM增减功能修复方案
后端代码修复(app.py)
原代码存在BPM未初始化、多用户数据冲突、路由返回页面导致刷新的问题,修复后代码如下:
from flask import Flask, render_template, request, jsonify, session app = Flask(__name__) app.secret_key = 'your_custom_secret_key' # 启用session必须设置密钥 # 初始化BPM,用session存储避免多用户干扰 def init_bpm(): if 'BPM' not in session: session['BPM'] = 100 # 默认初始值设为100 def setBPM(current, change=0): # 替换原位运算逻辑,用清晰的条件判断 if change > 0 and current < 200: return current + change elif change < 0 and current > 30: return current + change return current # 不满足增减条件时返回原值 @app.route('/pulse') def pulse(): init_bpm() return render_template("pulse.html") @app.route('/pulseUP', methods=['POST']) def pulseUp(): init_bpm() session['BPM'] = setBPM(session['BPM'], 10) return jsonify({'bpm': session['BPM']}) # 返回JSON格式的最新BPM值 @app.route('/pulseDOWN', methods=['POST']) def pulseDwn(): init_bpm() session['BPM'] = setBPM(session['BPM'], -10) return jsonify({'bpm': session['BPM']}) @app.context_processor def get_BPM_var(): init_bpm() return dict(get_BPM_var=session['BPM']) if __name__ == "__main__": app.run(debug=True)
前端代码修复(pulse.html)
原代码存在未引入jQuery、用form提交导致刷新、AJAX事件绑定错误的问题,修复后代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=800px, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"> <!-- 引入jQuery,否则无法使用AJAX功能 --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div class="parent"> <div class="child"> <div id="grid-pulse"> <div class="cell-pulse"> <!-- 替换form提交为普通按钮,避免页面刷新 --> <button id="btn-up">+</button> </div> <div class="cell-pulse"></div> <div class="cell-pulse"> <div class="numbkgnd"> <h3 id="BPMID">{{ get_BPM_var }}<br>BPM</h3> </div> </div> <div class="cell-pulse"></div> <div class="cell-pulse"> <button id="btn-down">-</button> </div> <div class="cell-pulse"></div> </div> </div> </div> <script> // 绑定+按钮的点击事件 $("#btn-up").click(function() { $.ajax({ url: "/pulseUP", type: "POST", success: function(response) { // 无刷新更新页面上的BPM显示 $("#BPMID").html(response.bpm + "<br>BPM"); }, error: function(xhr) { console.log("请求失败"); } }); }); // 绑定-按钮的点击事件 $("#btn-down").click(function() { $.ajax({ url: "/pulseDOWN", type: "POST", success: function(response) { $("#BPMID").html(response.bpm + "<br>BPM"); }, error: function(xhr) { console.log("请求失败"); } }); }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Nicholas T
相关产品推荐
相关产品推荐

