14

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

Brad Koch
  • 19,267
  • 19
  • 110
  • 137
Robin
  • 634
  • 1
  • 7
  • 18
  • How about `content = request.form['content']`? :) – favoretti Feb 26 '13 at 03:11
  • @favoretti can't work: `BadValueException: Bad value for field of type "content". Reason: "Value is not an instance of (got: list)"` – Robin Feb 26 '13 at 03:19
  • Ok, and what does `request.form.getlist('content')` return? A bit more specifics about 'is not work' could help. Don't have a flask handy here to test unfortunately. – favoretti Feb 26 '13 at 03:25
  • it's return the same error as `request.form['content']` . ps: post data in firebug may help. – Robin Feb 26 '13 at 03:40

2 Answers2

17

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']
Audrius Kažukauskas
  • 13,173
  • 4
  • 53
  • 54
2

If you inspect the POST being submitted by jQuery, you will most likely see that content is actually being passed as content[]. To access it from the Flask's request object, you would then need to use request.form.getlist('content[]').

If you would prefer to have it passed through as content, you can add traditional: true to your $.ajax() call.

More details about this can be found in the 'data' and 'traditional' sections of http://api.jquery.com/jQuery.ajax/.

dirn
  • 19,454
  • 5
  • 69
  • 74
  • when i set `traditional: true` to $.ajax. i received a string like `[object Object]` in server... but it's not what i want :( – Robin Feb 26 '13 at 04:04
  • Different server side technologies handle that differently. You may want to check out the answer about JSON provided by Audrius. – dirn Feb 26 '13 at 12:29