Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON "POST" to Flask View doesn't work

Tags:

I want to send some JSON via POST to my Flask View.

here is my code

js:

$.post('/blog/add/ajax',
  { "title": "hallo", "article": "test" },
  function(data) {
    console.log(data.title);
    console.log(data.article);
  },
  "json"
);

py:

@app.route('/blog/add/ajax', methods=['POST', 'GET'])
def add_blog_ajax():
    if request.method == 'POST':
        title = request.json['title']
        article = request.json['article']
        blog = Blog(title, article)
        db.session.add(blog)
        db.session.commit()
        return jsonify(title=title, article=article)

error:

TypeError: 'NoneType' object has no attribute '__getitem__'

i dont know what to do, and whats going wrong here.

like image 923
cebor Avatar asked Jan 04 '13 18:01

cebor


1 Answers

Ok I got a solution:

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "/blog/add/ajax",
  data: JSON.stringify({title: 'hallo', article: 'test'}),
  success: function (data) {
    console.log(data.title);
    console.log(data.article);
  },
  dataType: "json"
});

This works for me now!

like image 113
cebor Avatar answered Oct 22 '22 21:10

cebor