Flask表单POST提交后下拉框选中值重置、AJAX提交仍刷新问题求助
问题修复方案
一、AJAX提交页面仍刷新的修复
你遇到的AJAX不生效问题有两个核心错误:
- jQuery选择器错误
你写的$('form1')是匹配标签名为form1的元素,而你的表单是name属性为form1,正确的选择器有两种写法:- 方案1:给form标签加id属性,修改HTML:
<form class="select-year" method="post" name="form1" id="form1">
然后AJAX代码里选择器改为$('#form1')
- 方案2:直接按name属性匹配,选择器写为
$('form[name="form1"]') - HTML标签语法错误
你当前的form和select开头标签多了自闭和斜杠<form .../>、<select .../>,这会导致DOM结构解析异常,事件绑定失效,直接删除开头标签末尾的斜杠即可:
<form class="select-year" method="post" name="form1" id="form1"> <label>Year From</label> <select name="year_pop_category" class="form-control mx-sm-3 my-2" id="year_pop_category"> <option value="2016">2016</option> <option value="2017">2017</option> <option value="2018">2018</option> </select> <button type="submit" class="btn btn-primary my-2">GO!</button> </form>
修正后可用的AJAX代码如下:
$(document).ready(function() { $('#form1').on('submit', function(e) { // 阻止默认提交行为放在最开头,避免代码报错时仍触发页面刷新 e.preventDefault(); $.ajax({ data: { year_from: $('#year_pop_category').val() }, type : 'POST', url : '/product', success : function(result){ alert(result.output); // 此处添加你更新页面数据的逻辑,替换原来展示数据的DOM内容 } }); }); });
二、如果不用AJAX,用普通表单提交的修复方案
普通提交页面刷新后下拉框重置,是因为HTML默认不会保留提交前的选中状态,需要后端渲染模板时回传选中值:
- 首先修改Flask后端代码,示例如下:
from flask import request, render_template @app.route('/product', methods=['GET', 'POST']) def product(): # 读取提交的年份参数,默认值设为2016 selected_year = request.form.get('year_pop_category', '2016') # 按选中年份查询对应数据 page_data = query_data_by_year(selected_year) # 渲染模板时把选中年份和数据一起传到前端 return render_template('你的模板文件名.html', selected_year=selected_year, page_data=page_data)
- 然后修改前端select部分代码,给对应option加
selected属性:
<select name="year_pop_category" class="form-control mx-sm-3 my-2" id="year_pop_category"> <option value="2016" {% if selected_year == '2016' %}selected{% endif %}>2016</option> <option value="2017" {% if selected_year == '2017' %}selected{% endif %}>2017</option> <option value="2018" {% if selected_year == '2018' %}selected{% endif %}>2018</option> </select>
内容的提问来源于stack exchange,提问作者Ray
相关产品推荐
相关产品推荐

