You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:18:04