在Python / Flask中访问HTML表单数据

时间:2018-11-25 23:08:10

标签: javascript python jquery ajax flask

我正在与一个使用Flask的项目的合作伙伴合作,该项目需要将(可变)JSON对象从HTML文件传递到app.py文件,从而查询我们的数据库。我的伙伴使用文本输入字段成功编码了该版本,并将检索到的记录打印到控制台。但是,自那时以来,我们在实现下拉菜单时已经进行了很多更改,因此我们无法再次使它们正常工作。

就目前而言,我能够ping app.py文件并返回一个虚拟响应(例如,向控制台打印“ hello”),但是我似乎无法访问通过传递的实际数据JSON对象。 (我什至还没有弄乱数据库,只是想操纵对象。)最近,我得到GET(url)500(内部服务器错误),而使用POST方法时也遇到了同样的情况。

我已经阅读了很多有关类似问题的讨论(仅举几个例子,hereherehere),并尝试了几种不同的方法。我想我肯定在表单上做错了,看来解决方案应该很简单,但是我不太想弄清楚它。

以下是相关的HTML和Javscript:

printf("trial %d took %lld (%lld cycles per call)\n", t, (y-x), (y-x)/loops);

这是Python代码:

<!-- establish the Flask form which will send the selected airports to the Python code and database -->
<form name="selected_route" id="selected_route" method="GET">

    <p>Departure</p>
    <p>
        <!-- dropdown menu for departure state -->
        <select name="departure_state" id="departure_state" onChange="changeDepAirport(this.value);">
        </select>

        <!-- dropdown menu for departure airport, generated by choice of state -->
        <select name="departure_airport" id="departure_airport">
        <option value="" disabled selected>Select an airport</option>
        </select>
    </p>

    <p>Arrival</p>
    <p>
        <!-- dropdown menu for arrival state -->
        <select name="arrival_state" id="arrival_state" onChange="changeArrivAirport(this.value);">
        </select>

        <!-- dropdown menu for arrival airport, generated by choice of state -->
        <select name="arrival_airport" id="arrival_airport">
        <option value="" disabled selected>Select an airport</option>
        </select>
    </p>

    <!-- submit button for the departure and arrival parameters, which will visualize the data for that route -->
    <p>
        <button name="go" id="go" type="submit" onclick="retrieveRouteData()">Go!</button>
    </p>
</form>

<script>
// function to retrieve the data for the selected route
function retrieveRouteData() {
    departure_airport = document.getElementById("departure_airport").value;
    arrival_airport = document.getElementById("arrival_airport").value;
    route_object = { "departure_airport" : departure_airport,
                        "arrival_airport" : arrival_airport};
    console.log(route_object);

    testAj(function(output){
        console.log("1")
        console.log(output)
    });

    function testAj(handleData) {
        $(document).ready(function() {
            $('form').submit(function (e) {
                var url = "{{ url_for('test') }}"; // send the data here
                $.ajax({
                    type: "GET",
                    url: url,
                    data: route_object,
                    success: function (data) {
                        console.log(data)  // display the returned data in the console.
                    }
                });
                e.preventDefault(); // block the traditional submission of the form.
            });
        });
    };
 };

 generateStateLists(); // calls the function to populate the initial dropdowns

 </script>

预先感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

在发送和设置调用的json标头之前,尝试对json数据进行字符串化,如下所示:

$.ajax({
                    type: "POST",
                    dataType: "json",
                    url: url,
                    data: JSON.stringify(route_object),
                    contentType: "application/json;charset=utf-8"
                    success: function (data) {
                        console.log(data)  // display the returned data in the console.
                    }
                });

答案 1 :(得分:0)

使用flask,您可以轻松访问HTML表单元素。检查以下代码。

HTML:

<form action="" method="POST">
    <label> Username </label>
    <input type="text" name="username" value={{request.form.username}}>
    <label> Password </label>
    <input type=”"password" name="password" value={{request.form.password}}>

    <button type=”submit”> Submit </button>
</form>

Python:

def login()
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        # code that uses the data you've got
        # in our case, checking if the user exists
        # and logs them in, if not redirect to sign up
    else:
        # an exception

基本上,您可以通过应该连接到数据库的request.form访问元素。

编辑: 如果要直接在Python中搜索表单元素,可以使用以下代码:

import cgi
form = cgi.FieldStorage()
searchterm =  form.getvalue('username')
searchterm =  form.getvalue('password')

答案 2 :(得分:0)

我认为问题出现在您的代码的以下行中:

var url = "{{ url_for('test') }}"; // send the data here

为了使用Jinja将数据传递给javascript,您可能需要转义数据。参见here

尝试并在您的JavaScript代码中打印出url的值,然后查看url是否正确