简体   繁体   English

JavaScript / Ajax动态更新WTForms选择字段

[英]JavaScript/Ajax to Dynamically Update WTForms Select Field

OK. 好。 I know this has been tackled many times but I can't find an answer with a useful example of javascript to use. 我知道这已被解决了很多次,但我找不到一个有用的javascript示例的答案。

Say I have this form: 说我有这个表格:

class MyForm(Form):
    category = SelectField("Category")
    issue = SelectField("Issue")

What I need is for whatever is selected in 'category' at runtime to determine what the user sees in the issue dropdown without a POST of any kind ocurring. 我需要的是在运行时在“类别”中选择的任何内容,以确定用户在问题下拉列表中看到的内容,而没有任何类型的POST。 I know how to dynamically create the choices in the view from my database query. 我知道如何从数据库查询中动态创建视图中的选项。 I even have gone so far as to create a dictionary of "issue choices" based off of category choices. 我甚至已经根据类别选择创建了“问题选择”字典。

I just can't for the life of me figure out the javascript I need so that on select of something from the category drop down determines whats in the issue dropdown. 我只是不能为我的生活找出我需要的JavaScript,以便从类别下拉菜单中选择一些东西确定问题下拉列表中的什么。

通过查看Flask jQuery AJAX示例中的示例,我找到了所需的信息 - 这是一个最小的工作示例,几乎是GIST或书籍章节。

I came up with an example very close to jsbueno's implementation. 我想出了一个非常接近jsbueno实现的例子。 You can find the Gist here. 你可以在这里找到Gist The .py file is a standalone example. .py文件是一个独立的示例。

In your html template use jquery to register an ajax request when you click the select field. 在您的html模板中,使用jquery在单击选择字段时注册ajax请求。 If the request is a success the html for the select field gets updated with the new select options (send as a response from the server). 如果请求成功,则选择字段的html将使用新的选择选项进行更新(作为来自服务器的响应发送)。 Look at the actual HTML generated by the template to see how the select field looks like. 查看模板生成的实际HTML,以查看选择字段的外观。

<form action="" method="post" id="selectDevice" name="device">
    Nummber of Devices: {{ form.selectAmount(size=1) }}
    Select device: {{form.deviceAddress() }}
</form>
<script type="text/javascript" charset="utf-8">
$("#deviceAddress").click(function(){
    $.ajax({
        url: '/selectform',
        type: 'POST',
        data: $('#selectDevice').serialize(),
        success: function(selectOptions){
            $("#deviceAddress").empty();
            for (var i = 0; i < selectOptions.length; i++){
                $("#deviceAddress").append(
                    $("<option></option>")
                    .attr("value", selectOptions[i][0])
                    .text(selectOptions[i][1])
                );
            }
        }
    });
});
</script>

On the server side, use a route for the ajax post request.`As example this route changes the options depending on another form field (the information got send over with the data tag in the ajax request). 在服务器端,使用ajax post请求的路由。例如,此路由根据另一个表单字段更改选项(通过ajax请求中的数据标记发送的信息)。 In WTForms the select field options is a list of tuples containing an ID and name, I kept this the same on the python side. 在WTForms中,选择字段选项是包含ID和名称的元组列表,我在python端保持相同。

@app.route('/selectform', methods=['POST'])
def updateselect():
    deviceAmount = int(request.form.get('selectAmount'))
    choices = [('device{}'.format(i), i) for i in range(deviceAmount)]
    response = make_response(json.dumps(choices))
    response.content_type = 'application/jsons'
    return response`

Only one remark: the ajax request is performed on dropping down and on collapsing. 只有一个注释:ajax请求是在下拉和折叠时执行的。 The last part is not necessary of course, there is probably a way to structure the jquery so it only requests on dropdown. 最后一部分当然不是必需的,可能有一种方法来构造jquery,因此它只在下拉列表中请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM