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

选中单选按钮提交后重定向URL的value显示为on如何解决

问题根因

你遇到的核心问题是单选框未设置value属性:浏览器对于未指定value的选中单选框,默认会提交on作为值,这就是你拿到的参数始终是on的原因。
另外你的Flask代码还存在一个隐藏问题:/operations/<warehouse>对应的视图函数名为get_buildings,但你调用url_for时使用的是get_operations,会触发端点不存在报错,需要同步函数名。


方案1:常规表单提交(推荐)

1. 修改HTML单选框代码

给所有单选框补充value属性,值为你要提交的仓库名称:

{% for value in values %}
    <label class="btn btn-outline-secondary col-1 text-center rounded px-3 m-1" for="{{ value }}">{{ value }}</label>
    <!-- 新增value属性 -->
    <input type="radio" class="btn-check" name="radio" id="{{ value }}" value="{{ value }}" autocomplete="off">
{% endfor %}

2. 修正Flask代码

同步url_for的端点名称,同时补充参数容错逻辑:

@select_warehouse_bp.route("/", methods=["GET", "POST"])
def get_home():
    # 用get方法取值,避免未选单选直接提交时报错,可自定义默认值
    warehouse = request.form.get('radio', 'default')
    # 同步视图函数名为get_buildings
    return redirect(url_for('select_warehouse_bp.get_buildings', warehouse=warehouse))


@select_warehouse_bp.route("/operations/<warehouse>", methods=["GET", "POST"])
def get_buildings(warehouse):
    return render_template("base.html")

方案2:前端直接跳转(无需后端处理表单)

如果不需要后端处理表单逻辑,可以直接用JS完成跳转,省去表单提交步骤:

1. 同上先给单选框补充value属性

2. 修改JS逻辑

阻止表单默认提交行为,直接读取选中值跳转即可:

function submitWarehouse(e){
    // 阻止表单默认提交
    e.preventDefault();
    // 读取选中单选框的value值
    const warehouse = $('input[name="radio"]:checked').val();
    // 直接跳转页面
    window.location.href = `/operations/${warehouse}`;
}

内容的提问来源于stack exchange,提问作者pandasmasta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:06:04