2013-10-19 90 views
2

我刚刚学习Flask。我试图通过一个jQuery调用来获得一个JSON对象。我的HTML这个样子的,在Flask函数中获取JSON数据

<html> 
    <head> 
    <title>Passenger</title> 
    <style type="text/css"></style> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
    </head> 
    <body> 
    <div> 
     <form onsubmit="return false"> 
     <input class="name" type="text" placeholder="Name"> 
     <input class="submit" type="submit" placeholder="Go"> 
     </form> 
    </div> 
    <script> 
    $("input.submit").click(function(e){ 
     $.post("/save", {name: $("input.name").val(), time: "2pm"}); 
    }); 
    </script> 
</body> 
</html> 

烧瓶应用程序文件的样子,

from flask import Flask 
from flask import redirect, url_for, jsonify 
from flask import request 
import json 
app = Flask(__name__) 

@app.route('/') 
def home(): 
    return redirect(url_for('static',filename='index.html')) 

@app.route('/save', methods=['PUT','POST']) 
def get_name(): 
    print request.json 
    return request.json 

if __name__=='__main__': 
    app.run(debug=True) 

运行这段代码返回无。我期待取回JSON对象[{name:$(“input.name”).val(),time:“2pm”}]。谢谢。

回答

6

问题是,jquery帖子没有使用json的数据类型。你可以通过打印出请求content_type来看到:

print request.content_type 
application/x-www-form-urlencoded; charset=UTF-8 

将Javascript更改为发布json,并且request.json应该按照您的预期填充json。

var data = JSON.stringify({name: $("input.name").val(), time: "2pm"}); 
$.ajax("/save", { 
    data: data, 
    contentType : "application/json", 
    type : "POST" 
}); 

注意改变JS代码后,request.content_type将应用程序/ JSON

+0

谢谢!得到它了。是否有可能将我返回的数据转换成json。在这种情况下,功能如何变化? – Nitin