jquery - 如何使用从 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
格式。模拟数据如下。将key
是value
,<option>
并且value
将text
是<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
)
解决方案
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
推荐阅读
- python - 如何在 Django 测试用例中使用正确的 oAuth2 重定向 URL?
- sql - 获取从未属于任何类别的ID
- ios - react-native 链接后类“RCTBridge”错误的重复接口定义
- nginx - nginx unicorn - POST flask_mail 502 错误和“忽略连接重置”
- ios - iMessage 无法识别 Open Graph 标签
- python - Django:如何使用与先前访问的模型关联的外键创建新模型
- python - 如何更改 pyplot 散点图的大小?
- android - 为 Android 生成共享库
- php - Symfony sonata EntityType 编辑表单 - 选择 - 获取其他当前
- php - 使 HTML 表格脱离多维数组的更好解决方案