如何将HTML表单select选项值传递至Flask?代码异常问题求助
问题根因
- 第一点:HTML表单标签的属性语法错误,导致提交请求类型不对
你的<form>标签里两个属性之间多写了英文逗号:<form action="{{url_for('check')}}",method="post">,浏览器无法识别method="post"配置,表单提交默认使用GET请求,所以请求到/check路由时直接走了else分支返回页面。 - 第二点:Flask路由POST分支的返回逻辑不符合规范
你写的return ('index.html', Operations)不是Flask支持的合法返回格式,要么直接返回选中的字符串,要么把选中的值传递给模板渲染才能在页面展示。 - 补充小问题:第二个下拉选项的显示文本有拼写错误
reult应为result,不过value值正确,不影响提交逻辑。
修复后的代码
Flask代码
from flask import Flask, request, render_template app = Flask(__name__) @app.route('/',methods=['GET']) def hello_world(): return render_template('index.html') @app.route('/check', methods=['GET','POST']) def check(): if request.method == 'POST': Operations = request.form['Operations'] # 将选中的操作传递给模板渲染展示 return render_template('index.html', selected_op=Operations) else: return render_template('index.html') if __name__ == '__main__': app.run(debug=True)
HTML代码
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Title</title> </head> <body> <h1 style="background-color:blue;" title="This is to run and check state of azure devops pipelines using one-click">Azure Devops Pipeline</h1> <hr> <!-- 新增展示选中操作的位置 --> {% if selected_op %} <p>你选中的操作是:*{{selected_op}}*</p> {% endif %} <p>Choose Options to perform operation on pipeline:</p> <!-- 去掉属性之间的逗号,修复method不生效问题 --> <form action="{{url_for('check')}}" method="post"> <Select name="Operations" id='Operations' required='required'> <option value="Run Pipeline">Run Pipeline</option> <option value="Check state and result of pipeline">Check state and result of pipeline</option> </Select><br><br> <button id="sub" type='submit'>Click me</button> </form> </body> <hr> </html>
内容的提问来源于stack exchange,提问作者Ali Haider
相关产品推荐
相关产品推荐

