Python 如何在flask中使用从ajax发布的数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14908864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:49:44  来源:igfitidea点击:

how can I use data posted from ajax in flask?

jquerypythonajaxflask

提问by thkang

I'm having trouble getting data POSTed from jquery ajax.

我在从 jquery ajax 获取数据时遇到问题。

$('#clickme').click( function() {
    var data = save_input(); // data

    data['_sid'] = $survey_id;  // survey_id injected from flask
    data['_uip'] = $user_ip; // user_ip injected from flask, request.remote_addr

    $.ajax({
        type : "POST",
        url : "{{ url_for('mod.load_ajax') }}",
        data: JSON.stringify(data),
        contentType: 'application/json;charset=UTF-8',
        success: function(result) {
            console.log(result);
        }
    });

    console.log(data);
});

from the code, datais a javascript object like

从代码来看,data是一个 javascript 对象,如

{
    'foo' : 'foo',
    'bar' : 'bar',
    'fo_' : 42,
}

what I'm trying to do in flask is :

我想在烧瓶中做的是:

@mod.route('/load_ajax', methods=["GET", "POST"])
def load_ajax():
    if request.method == "POST":
        # load _sid and _uip from posted JSON and save other data
        # but request.form is empty.
        # >>> request.form
        # ImmutableMultiDict([]) 
        return str(request.form)

see, the ajax request is made but no data is submitted. I do console.log(data)with ajax so I can see that I really have some meaningful data in datavariable in jquery. but request.form in ajax view is empty. Where is my data submitted?

看, ajax 请求已发出,但没有提交数据。我console.log(data)使用 ajax,所以我可以看到我data在 jquery中的变量中确实有一些有意义的数据。但是 ajax 视图中的 request.form 是空的。我的数据在哪里提交?

采纳答案by phabtar

Try

尝试

 $.ajax({
    type : "POST",
    url : "{{ url_for('mod.load_ajax') }}",
    data: JSON.stringify(data, null, '\t'),
    contentType: 'application/json;charset=UTF-8',
    success: function(result) {
        console.log(result);
    }
});

Then from the server, you can refer to the variables in data like this :

然后从服务器,您可以像这样引用数据中的变量:

request.json['foo']

Since the content type is specified as application/jsonthe data is in request.json

由于内容类型被指定为application/json数据在request.json

回答by Ifthikhan

As per your example you are not sending a key value pair but rather assigning a JSON string to the jQuery data option. As mentioned in the comments you have to stringify your JSON, create an object with a key (which will be used to access the JSON string from flask) and then assign it to the jQuery data key.

根据您的示例,您不是发送键值对,而是将 JSON 字符串分配给 jQuery 数据选项。如评论中所述,您必须对 JSON 进行字符串化,创建一个带有键的对象(将用于从 Flask 访问 JSON 字符串),然后将其分配给 jQuery 数据键。

    $.ajax({
            type : "POST",
            url : "{{ url_for('mod.load_ajax') }}",
            data: {json_str: JSON.stringify(data)},
            contentType: 'application/json;charset=UTF-8',
            success: function(result) {
                console.log(result);
            }
        });

    @mod.route('/load_ajax', methods=["GET", "POST"])
    def load_ajax():
        if request.method == "POST":
            # load _sid and _uip from posted JSON and save other data
            # but request.form is empty.
            # >>> request.form
            # ImmutableMultiDict([]) 
            return str(request.form['json_str']
     )

回答by Granit

Have you tried remove contentType? You suppose to post data to Flask.

您是否尝试过删除 contentType?您假设将数据发布到 Flask。

could you try add fake data like

你能尝试添加假数据吗

data:{"hello":"world"} inside ajax? just to check if the hello world arrive to request.form

数据:{"hello":"world"} 在 ajax 中?只是为了检查 hello world 是否到达 request.form

回答by Patrick Mutuku

On the flask side, use:

在烧瓶侧,使用:

data = request.get_json()

The variable data now has the dictionary you sent using ajax and you can now manipulate it with python

变量数据现在包含您使用 ajax 发送的字典,您现在可以使用 python 操作它