如何在Flask Python中获取复选框的选中与未选中值
解决Flask中获取所有复选框(选中/未选中)状态的问题
嘿,这个问题我之前也碰到过!默认情况下HTML表单只会提交被选中的复选框数据,未选中的复选框根本不会把状态传到后端,所以你只能拿到选中的值。别担心,这里有两种实用的解决方案,你可以按需选择:
方法一:用JavaScript收集所有状态,通过AJAX提交
这种方法灵活性更高,适合需要异步处理的场景。我们可以在表单提交前用JS遍历所有复选框,把每个框的状态都收集起来,再发送给后端。
修改后的sample.html
<!DOCTYPE html> <html lang="en"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="statusForm" method="post" action="/tr"> <!-- 给每个复选框加唯一标识,方便区分不同选项 --> <input type="checkbox" class="openprom" data-id="1" value="yes"> 选项1 <input type="checkbox" class="openprom" data-id="2" value="yes"> 选项2 <input type="submit" value="提交"> </form> <script> $(document).ready(function(){ // 监听表单提交事件,阻止默认刷新提交 $('#statusForm').submit(function(e){ e.preventDefault(); let allCheckboxStatus = []; // 遍历所有复选框,收集每个框的状态 $('.openprom').each(function(){ allCheckboxStatus.push({ checkbox_id: $(this).data('id'), is_checked: $(this).is(':checked'), value: $(this).is(':checked') ? 'yes' : 'no' }); }); // 用AJAX把整理好的状态数据发送到后端 $.post('/tr', { all_ses: JSON.stringify(allCheckboxStatus) }, function(response){ alert('提交成功!'); console.log(response); // 如果需要跳转页面,取消下面的注释 // window.location.href = '/tr'; }); }); }); </script> </body> </html>
修改后的sample.py
from flask import Flask, request, render_template import json app = Flask(__name__) @app.route('/') def home(): return render_template("pass_arr.html") @app.route('/tr', methods=['POST','GET']) def tr(): if request.method == 'POST': # 解析前端传来的JSON格式状态数据 all_ses = json.loads(request.form.get('all_ses')) print("所有复选框状态:", all_ses) # 输出示例:[{"checkbox_id": "1", "is_checked": true, "value": "yes"}, {"checkbox_id": "2", "is_checked": false, "value": "no"}] return "welcome" if __name__ == "__main__": app.run(debug=True)
方法二:用隐藏输入框记录未选中状态
如果不想用AJAX,也可以给每个复选框配对一个隐藏输入框。当复选框未选中时,隐藏框会提交默认的"未选中"值;选中时,复选框的值会覆盖隐藏框的值(同名输入框中,选中的复选框优先级更高)。
修改后的sample.html
<!DOCTYPE html> <html lang="en"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" action="/tr"> <!-- 每个复选框前加同名隐藏输入框,默认值为no --> <input type="hidden" name="ses[]" value="no"> <input type="checkbox" class="openprom" name="ses[]" value="yes"> 选项1 <input type="hidden" name="ses[]" value="no"> <input type="checkbox" class="openprom" name="ses[]" value="yes"> 选项2 <input type="submit" value="提交"> </form> <script> // 保留原来的点击提示逻辑 $(document).ready(function(){ $('.openprom').click(function(){ if($(this).prop("checked") == true){ alert("Checkbox is checked."); } else if($(this).prop("checked") == false){ alert("unchecked"); } }); }); </script> </body> </html>
修改后的sample.py
from flask import Flask, request, render_template app = Flask(__name__) @app.route('/') def home(): return render_template("pass_arr.html") @app.route('/tr', methods=['POST','GET']) def tr(): if request.method == 'POST': # 获取所有复选框的状态(包括未选中的) all_ses = request.form.getlist('ses[]') print("所有复选框状态:", all_ses) # 输出示例:如果第一个选中、第二个未选中,会得到 ['yes', 'no'] return "welcome" if __name__ == "__main__": app.run(debug=True)
小提示
- 方法二中,隐藏框和复选框的
name必须完全一致,且顺序要对应(隐藏框在前,复选框在后),这样选中时复选框的值才能正确覆盖隐藏框的值。 - 如果需要精准区分每个复选框,可以把
name改成带索引的格式,比如ses[0]、ses[1],后端就能通过字典形式获取对应选项的状态了。
内容的提问来源于stack exchange,提问作者user9501250
相关产品推荐
相关产品推荐

