Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post data structure like json to flask?

I have a data structure like this:

enter image description here

I'm try to send it to server by $.ajax:

$.ajax({
    type: 'POST',
    data: post_obj, //this is my json data
    dataType: 'json',
    url: '',
    success: function(e){
       console.log(e);
    }
});

and I want get it in server by flask: title = request.form['title'] working fine!

But how do I get content ?

request.form.getlist('content') doesn't work.

This is the post data in firebug:

enter image description here

Thanks a lot :D

like image 844
Robin Avatar asked Feb 26 '13 03:02

Robin


1 Answers

You are sending your data encoded as query string instead of JSON. Flask is capable of processing JSON encoded data, so it makes more sense to send it like that. Here's what you need to do on the client side:

$.ajax({
    type: 'POST',
    // Provide correct Content-Type, so that Flask will know how to process it.
    contentType: 'application/json',
    // Encode your data as JSON.
    data: JSON.stringify(post_obj),
    // This is the type of data you're expecting back from the server.
    dataType: 'json',
    url: '/some/url',
    success: function (e) {
        console.log(e);
    }
});

On the server side data is accessed via request.json (already decoded):

content = request.json['content']
like image 198
Audrius Kažukauskas Avatar answered Oct 22 '22 08:10

Audrius Kažukauskas