这是与WTForms本机功能一起使用的此逻辑的示例实现。这里的技巧是,如果要使用WTForms验证,则需要使用每个可能的值实例化表单,然后修改Javascript中的可用选项以基于其他选择显示过滤后的值。
在此示例中,我将使用州和县的概念(我处理了大量地理数据,因此这是我构建的常见实现)。
这是我的表单,我为重要元素分配了唯一ID,以便从Javascript访问它们:
class PickCounty(Form): form_name = HiddenField('Form Name') state = SelectField('State:', validators=[DataRequired()], id='select_state') county = SelectField('County:', validators=[DataRequired()], id='select_county') submit = SubmitField('Select County!')现在,Flask视图实例化并处理表单:
@app.route('/pick_county/', methods=['GET', 'POST'])def pick_county(): form = PickCounty(form_name='PickCounty') form.state.choices = [(row.ID, row.Name) for row in State.query.all()] form.county.choices = [(row.ID, row.Name) for row in County.query.all()] if request.method == 'GET': return render_template('pick_county.html', form=form) if form.validate_on_submit() and request.form['form_name'] == 'PickCounty': # pre to process form flash('state: %s, county: %s' % (form.state.data, form.county.data)) return redirect(url_for('pick_county'))Flask视图以响应对县的XHR请求:
@app.route('/_get_counties/')def _get_counties(): state = request.args.get('state', '01', type=str) counties = [(row.ID, row.Name) for row in County.query.filter_by(state=state).all()] return jsonify(counties)最后,将Javascript放在Jinja模板的底部。我假设因为您提到了Bootstrap,所以您正在使用jQuery。我还假设这是在线javascript,所以我使用Jinja返回端点的正确URL。
<script charset="utf-8" type="text/javascript">$(function() { // jQuery selection for the 2 select boxes var dropdown = { state: $('#select_state'), county: $('#select_county') }; // call to update on load updateCounties(); // function to call XHR and update county dropdown function updateCounties() { var send = { state: dropdown.state.val() }; dropdown.county.attr('disabled', 'disabled'); dropdown.county.empty(); $.getJSON("{{ url_for('_get_counties') }}", send, function(data) { data.forEach(function(item) { dropdown.county.append( $('<option>', { value: item[0], text: item[1] }) ); }); dropdown.county.removeAttr('disabled'); }); } // event listener to state dropdown change dropdown.state.on('change', function() { updateCounties(); });});</script>


