简体   繁体   English

在传递到Flask应用之前编辑表单数据

[英]Editing form data before passing into flask app

I have the following multiple selection form which is rendered by a flask app: 我有以下烧瓶应用程序呈现的多选表格:

<form method="POST" action="">
    <label for="sports">Sports:</label>
    <select id="sports" name="sports" multiple>
        <option value="Basketball">Basketball</option>
        <option value="Football">Football</option>
        <option value="Baseball">Baseball</option>
        <option value="Golf">Golf</option>
        <option value="Soccer">Soccer</option>
    </select>
    <input type="submit" name="send" onclick="var selected_sports = project.getSelectedValues(document.querySelector('#sports'));">
</form>

I'm trying to send the data in the form of a list to the server / python code. 我正在尝试将列表形式的数据发送到服务器/ python代码。

For example, if you select Basketball, Football and Golf the list will be ["Basketball", "Football", "Golf"] and if you select only Football the list will be ["Football"] . 例如,如果选择["Basketball", "Football", "Golf"] ,则列表为["Basketball", "Football", "Golf"] ,如果仅选择["Basketball", "Football", "Golf"]则列表为["Football"]

I'm able to create the list using javascript (code below) but I'm not sure how to pass this created list to the server (the server is receiving only the first selected option). 我可以使用javascript(下面的代码)创建列表,但不确定如何将创建的列表传递给服务器(服务器仅接收第一个选择的选项)。

JS code to create list of selected values (called in HTML form when submit button is clicked): JS代码以创建所选值的列表(单击“提交”按钮时以HTML形式调用):

project = {};

project.getSelectedValues = function (selectTag) {
    var result = [];
    var options = selectTag && selectTag.options;

    for (var = 0; i < options.length; i++) {
        if (options[i].selected) {
            result.push(options[i].value || options[i].text);
        }
    }
    return result;
}

the server is receiving only the first selected option 服务器仅接收第一个选择的选项

You can submit the <select id="sports" name="sports" multiple> normally (without using JS to create a list) and reference all of the selected options in your python code by using getlist() 您可以正常提交<select id="sports" name="sports" multiple> (无需使用JS创建列表),并使用getlist()引用python代码中所有选定的选项

sports = request.form.getlist('sports')

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

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