如何用 ajax 调用返回的数据填充特定的 SelectField?
How to fill specific SelectField with the data returned from ajax call?
稍后更新...我的问题终于解决了。我只是想知道是否有办法做到这一点 更多 优雅?
我刚开始使用 Python3
、Flask
和 Jquery
进行编程。
我的目标是让一个 SelectField
根据另一个 SelectField
的选项更改其值。就像,当我选择美国作为国家/地区时,然后使用 ajax 帮助从数据库中自动加载状态(例如,New York/Washington、D.C./...)。
现在我可以使用 ajax 调用获取数据,这意味着我可以在浏览器的调试模式下看到响应。我只是不知道如何用响应数据填充特定的 SelectField
。下面是相关的代码片段。在此先感谢您的时间。
choose.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}
)
form.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
更新-1:
数据为 json
格式。下面的模拟数据。 key
将是 <option>
的 value
,而 value
将是 <option>
的 text
。
{
"bash", "desc_for_bash",
"csh", "desc_for_csh",
...
}
更新 2:
在@Deepak 的帮助下,我终于解决了这个问题。我在@Deepak 的回答(表单不接受 select 选项)下提到的问题 post 是错误的。事实上,form
确实接受了我的 html
页面上的 select 选项。我对其进行调试,发现我错过了在我的操作函数中重置 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
)
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
稍后更新...我的问题终于解决了。我只是想知道是否有办法做到这一点 更多 优雅?
我刚开始使用 Python3
、Flask
和 Jquery
进行编程。
我的目标是让一个 SelectField
根据另一个 SelectField
的选项更改其值。就像,当我选择美国作为国家/地区时,然后使用 ajax 帮助从数据库中自动加载状态(例如,New York/Washington、D.C./...)。
现在我可以使用 ajax 调用获取数据,这意味着我可以在浏览器的调试模式下看到响应。我只是不知道如何用响应数据填充特定的 SelectField
。下面是相关的代码片段。在此先感谢您的时间。
choose.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}
)
form.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
更新-1:
数据为 json
格式。下面的模拟数据。 key
将是 <option>
的 value
,而 value
将是 <option>
的 text
。
{
"bash", "desc_for_bash",
"csh", "desc_for_csh",
...
}
更新 2:
在@Deepak 的帮助下,我终于解决了这个问题。我在@Deepak 的回答(表单不接受 select 选项)下提到的问题 post 是错误的。事实上,form
确实接受了我的 html
页面上的 select 选项。我对其进行调试,发现我错过了在我的操作函数中重置 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
)
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