【发布时间】:2021-10-24 19:36:51
【问题描述】:
我有一个带有相应单选按钮的无序列表。选择单选按钮并按下提交按钮后,我想获取该值并在重定向的 url 中使用它。表单提交成功,但是,它返回的值是“on”/operations/on,而不是选择的实际值。我已经尝试使用常规方法=POST 以及 ajax 来返回该值,但没有运气。
HTML:
<form id="warehouse-selection-form" action="/" method="post">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="tab-content mb-4" id="myTabContent">
{% for key, values in warehouses.items() %}
<div class="tab-pane fade" id="{{ key.lower().replace('-', '').replace(' ', ' ').replace(' ', '-') }}" role="tabpanel" aria-labelledby="{{ key.lower().replace('-', '').replace(' ', ' ').replace(' ', '-') }}-tab">
{% for value in values %}
<label class="btn btn-outline-secondary col-1 text-center rounded px-3 m-1" for="{{ value }}">{{ value }}</label>
<input type="radio" class="btn-check" name="radio" id="{{ value }}" autocomplete="off">
{% endfor %}
</div>
{% endfor %}
</div>
<button id="submit" style="display:none;" class="btn btn-primary" onclick="submitWarehouse()">Submit</button>
</form>
烧瓶:
@select_warehouse_bp.route("/", methods=["GET", "POST"])
def get_home():
warehouse = request.form['radio']
return redirect(url_for('select_warehouse_bp.get_operations', warehouse=warehouse))
@select_warehouse_bp.route("/operations/<warehouse>", methods=["GET", "POST"])
def get_buildings(warehouse):
return render_template("base.html")
AJAX:
- 如果使用此方法和 method=post,请删除 CSRF 令牌
- 我也尝试使用 location.href 进行重定向以避免传回服务器,但没有成功。
function submitWarehouse(){
let warehouse = $('input[name="radio"]:checked').attr('id');
$.ajax({
url: `/operations/${warehouse}`,
type: "POST",
data: JSON.stringify({warehouse: warehouse}),
dataType: 'json',
success: function () {
alert('success');
},
error: function () {
alert('fail');
}
});
}
【问题讨论】:
-
您在无线电标签中忘记了
value="{{ value }}"。
标签: javascript html ajax flask