首页 > 解决方案 > 如何使用从 ajax 调用返回的数据填充特定的 SelectField?

问题描述

稍后更新...我终于解决了我的问题。我只是想知道是否有一种 优雅的方法?

我刚开始使用Python3,Flask和进行编程Jquery

我的目标是让一个人SelectField根据另一个SelectField人的选择来改变它的价值。就像,当我选择美国作为国家时,然后在 ajax 帮助下自动从数据库中加载州(例如,纽约/华盛顿,DC/...)。

现在我可以使用 ajax 调用获取数据,这意味着我可以在浏览器的调试模式下看到响应。我只是不知道如何SelectField用响应数据填充具体内容。下面是相关的代码片段。在此先感谢您的时间。

选择.html

<html>
<head>...</head>
<body>
...
<div class="row">
  <form action="{{url_for('some_view_function')}}" method="post">
    ...
    <div class="col-md-4 col-sm-4 col-xs-12">
      {{ form.country(class="form-control select2_single") }}
    </div>
    <div class="col-md-4 col-sm-4 col-xs-12">
      {{ form.state(class="form-control select2_single") }}
    </div>
    ...
  </form>
</div>
...
<script>
    $(document).ready(function(){
      $("#country").change(function(){
          country_id=$("#country").val();
          $.get("{{ url_for('get_states_by_country') }}",
                {"country_id":country_id},
                function(data, status){
                    if (status == 'success') {
                        // What should I do here with data?
                    }
          });
      });
  });
</script>
</body>
</html>

view_function.py

@app.route('/obtain/states', methods={'GET', 'POST'})
def get_states_by_country():
    country_id = request.args.get("country_id")

    states = State.query.filter_by(
        country_id=country_id
    )
    return jsonify(
        {int(s.state_id): s.state_name
         for s in states}
    )

表格.py

class LinkChooseForm(Form):
    country = SelectField(label='Country')
    state = SelectField(label='State')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.country.choices = [(c.id, c.name) for c in Country.query.all()]
        self.state.choices = [] # I leave it empty when initiating

Update-1:
数据是json格式。模拟数据如下。将keyvalue<option>并且valuetext<option>

{
  "bash", "desc_for_bash",
  "csh", "desc_for_csh",
  ...
}   

Update-2:
在@Deepak 的帮助下,我终于解决了这个问题。我在@Deepak 的回答(表单不接受选择选项)下提到的问题是错误的。事实上,form确实接受我html页面上的选择选项。我调试它并发现我错过了state.choices在我的动作函数中重置。您可能会注意到我state.choices在启动表单对象时将其留空。但是flask-wtf会验证如果您在页面上的选择是state.choices. 这显然不是,因为我把它留空了。所以我必须重置它request.form.get('state')以满足flask-wtf的验证。下面是提交功能。

@app.route('/test', methods={'GET', 'POST'})
def some_view_function():
    form = LinkChooseForm(**request.view_args)

    if request.method == 'POST':
        # The most important part here.
        form.state.choices = [(request.form.get('state'), "")]

        if form.validate_on_submit():
            action_entity = ActionEntity()
            action_entity.do(form)
            return redirect(url_for('.another_view_function'))
        else:
            # reset it as empty again
            form.state.choices = []

    return render_template(
        'result.html',
        form=form
    )

标签: jqueryajaxpython-3.xflask-wtforms

解决方案


var data = '{"bash":"desc_for_bash","csh":"desc_for_csh, city"}';//Your JSON data
data = JSON.parse(data);                                        //To parse your JSON data
var str=''
for(d in data)
str+='<option value="'+d+'">'+data[d]+'</option>'

$("#your_select_id").html(str)                                 //For adding options to select

推荐阅读