我该如何使用贴从阿贾克斯在瓶中的数据? [英] how can I use data posted from ajax in flask?

查看:153
本文介绍了我该如何使用贴从阿贾克斯在瓶中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有从jQuery的AJAX HTTP POST的麻烦数据。

I'm having trouble getting data POSTed from 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);
});

从code,数据就像

{
    '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)

看,Ajax请求作出,但没有数据被提交。我做的的console.log(数据)与阿贾克斯这样我就可以看到,我真的有在数据的一些有意义的数据变量jQuery中。但在的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 data variable in jquery. but request.form in ajax view is empty. Where is my data submitted?

推荐答案

尝试

 $.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']

由于内容类型被指定为应用程序/ JSON 中的数据是在 request.json

这篇关于我该如何使用贴从阿贾克斯在瓶中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆