简体   繁体   English

使用Ajax将数据传递到烧瓶

[英]Passing data into flask using Ajax

i am trying to pass some data from html to python using ajax using post request. 我正在尝试使用post请求使用ajax将一些数据从html传递到python。 But the arguments for request are empty. 但是请求的参数为空。

A simple endpoint, i am trying to print all the arguments that come in the form of request. 一个简单的端点,我正在尝试打印以请求形式出现的所有参数。

@app.route("/enter", methods=["POST", "GET"])
def enter_data():
    if request.method == "GET":
        return render_template('index.html')
    else:
        print("post")
        print(request.args)
        return render_template('index.html')

debug output 调试输出

post

ImmutableMultiDict([])
127.0.0.1 - - [22/Sep/2016 00:40:12] "POST /enter HTTP/1.1" 200 -

the ajax function is as below Ajax功能如下

$(function() {
    $('.button').click(function() {
        var user = $('#userinput').val();
        console.log(user);
        $.ajax({
            url: '/enter',
            data: JSON.stringify( {'user': $('#userinput').val()} ),
            type: 'POST',
            success: on_request_success,
            error: on_request_error,
            })
        });
    });

the value gets printed in js console. 该值将在js控制台中打印。 But its not present on python side. 但是它不在python端。

html code HTML代码

<body>
        <h3>The Chef Bucket</h3>
        Enter food you like to order.
        <input type="text" name="user_data" id="userinput" />
        <input type="button" value="Submit" class="button">

        <div id="userinputdata"> 
            {% if not entered %}
                <h4></h4>
            {% else %}
                <h4>{{ entered }}</h4>
            {% endif %}
        </div>

    </body>

您的html代码中没有<form>标记,因此您的$('form').serialize()执行任何操作。

Within render template, you need to specify elements to be filled in within your template. 在渲染模板中,您需要指定要在模板中填写的元素。

Instead of this; 代替这个;

@app.route("/enter", methods=["POST", "GET"])
def enter_data():
    if request.method == "GET":
        return render_template('index.html')
    else:
        print("post")
        print(request.args)
        return render_template('index.html')

Try this; 尝试这个;

@app.route("/enter", methods=["POST", "GET"])
def enter_data():
    if request.method == "GET":
        return render_template('index.html')
    elif request.method == "POST":
        entered = request.form['entered']
        return render_template('index.html', entered=entered)
    else:
        return render_template('index.html')

There is no <form> tag in your html code. 您的html代码中没有<form>标记。 Therefore your data attribute of the ajax is request is empty. 因此,您的ajax的data属性为request为空。 Either put your <div> in a <form> environment in the html or set your data attribute in the ajax request by hand: 可以将<div>放在html的<form>环境中,也可以手动在ajax请求中设置data属性:

$(function() {
    $('.button').click(function() {
        var user = $('#userinput').val();
        console.log(user);
        $.ajax({
            url: '/enter',
            data: JSON.stringify( {'user': $('#userinput').val()} ),
            type: 'POST',
            success: on_request_success,
            error: on_request_error,
            })
        });
    });

Note that the data attribute is here sent as an json object which you have to deserialize on the server side. 请注意,此处的data属性作为json对象发送,您必须在服务器端反序列化。 If you want to keep it simple, just define it as a dictinary. 如果要保持简单,只需将其定义为字典即可。

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

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