2013-01-04 5 views
14

Ich möchte etwas JSON per POST zu meinem Flask View senden.JSON "POST" zu Flask Ansicht funktioniert nicht

hier ist mein 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) 

Fehler:

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

ich weiß nicht, was zu tun ist und was falsch gehen Hier.

+0

Basierend auf dem Fehler, würde ich vorschlagen, dass request.json nicht richtig ausgefüllt ist. Können Sie den 'request.body' und Header ausgeben. Vielleicht senden Sie nicht den richtigen Inhaltstyp. – sberry

+0

Hat der 'request.body' Inhalt? – sberry

+0

@sberry jup gibt es Inhalt – cebor

Antwort

16

Ok habe ich eine Lösung:

$.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" 
}); 

Das funktioniert jetzt für mich!

+1

Beachten Sie, dass der 'contentType' angegeben wurde. – Xavi

+0

Eine leichte Abkürzung besteht darin, 'JSON.stringify' für das Objekt zu verwenden, das als 'data' übergeben werden soll. Also wäre Ihr Datenparameter gleich 'JSON.stringify ({title: 'hallo', article: 'test'})' – Matt