Flask开发中如何将HTML按钮对应的id值传递给后端Python函数
解决方案
有两种常用实现方式,可根据需求选择:
方案1:表单隐藏域传值(无需修改路由路径)
- 修改HTML模板代码
在每个循环生成的form中添加隐藏input字段存储对应id值,同时移除重复的id属性(HTML中同一页面id不能重复):
{% for i in range(length) %} <form action="{{ url_for('detail') }}" method="GET"> <input type="hidden" name="id" value="{{ id[i] }}"> <button type="submit" class="submit-btn-choice" style="margin-top: 20px;">Name</button> </form> {% endfor %}
- 修改detail视图函数
从GET请求参数中提取id值:
from flask import request @app.route('/detail', methods=['POST', 'GET']) def detail(): id = request.args.get('id') response = Coup_data(id) return render_template('detail.html', response =response )
方案2:URL路径参数传值
- 先修改detail路由配置,添加路径参数占位符:
@app.route('/detail/<id>', methods=['POST', 'GET']) def detail(id): response = Coup_data(id) return render_template('detail.html', response =response )
- 修改HTML模板代码,生成表单提交路径时直接传入对应id:
{% for i in range(length) %} <form action="{{ url_for('detail', id=id[i]) }}" method="GET"> <button type="submit" class="submit-btn-choice" style="margin-top: 20px;">Name</button> </form> {% endfor %}
可选优化
原Ongoing视图中无需单独传递length参数,且避免使用id作为变量名(id是Python内置函数,易引发冲突),可简化为:
@app.route('/Ongoing', methods=['POST', 'GET']) def Ongoing(): id_list = ['1', '2', '3', '4', '5', '6', '7', '8'] return render_template('Run.html', id_list=id_list)
模板循环可直接遍历数组,减少索引错误概率:
{% for item in id_list %} <form action="{{ url_for('detail', id=item) }}" method="GET"> <button type="submit" class="submit-btn-choice" style="margin-top: 20px;">Name</button> </form> {% endfor %}
内容的提问来源于stack exchange,提问作者ZSA
相关产品推荐
相关产品推荐

