flask app中从前端接受json的数据,但是flask的request中并没有接受成功,其中没有数据,换了很多函数都行不通。
js代码
$(function(){
$("#test").click(function(){
$.ajax({
url: "{{ url_for('main.getjson') }}",
type: "POST",
data: JSON.stringify({
"n1": "test1",
"n2": "test2",
"n3": "test3"
}),
dataType: "json",
success: function(data){
var a = data.user
var texthtml = "<p>" + a + "</p>"
$("#result").html(texthtml)
}
});
});
});
flask中的视图函数:
@main.route('/getjson', methods = ['GET', 'POST'])
def getjson():
a = request.json
if a:
return jsonify(user = "Right")
return jsonify(user = "error")
仅仅判断request.json是不是存在,但是返回来的总是“error”的字符串。request.json中总是null。后来换了request.args.get(),同样行不通。到底是哪里出错了,真心求教。
高洛峰2017-05-18 11:03:48
找到答案了,仅仅是在jquery部分出了问题。$.ajax的参数contentType,默认是 "application/x-www-form-urlencoded",需要把这个参数设置成application/json。
$.ajax({
url: "{{ url_for('main.getjson') }}",
type: "POST",
data: JSON.stringify({
"n1": "test1",
"n2": "test2",
"n3": "test3"
}),
contentType: "application/json",
dataType: "json",
success: function(data){
var a = data.user
var texthtml = "<p>" + a + "</p>"
$("#result").html(texthtml)
}
});
参考:https://flask.readthedocs.io/...
http://stackoverflow.com/ques...
迷茫2017-05-18 11:03:48
根据你的描述,你的已经把问题找到了,为什么不继续尝试一下,或者看下文档
@app.route('/api', methods=['POST'])
def api():
a = request.json
b = request.get_data()
c = request.values
print a
print b
print c
if a:
return 'ok'
return 'error one'
输出结果
None
{"id":1}
CombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([('{"id":1}', u'')])])
request.json很奇葩,确实没数据,但是它是可以用的,你这里没用的原因如下:
json If the mimetype is application/json this will contain the parsed
JSON data. Otherwise this will be None. The get_json() method should
be used instead.
但是我使用get_json(),它无情的报错说AttributeError: 'Request' object has no attribute 'get_json'
所以我只是成功使用过一次request.json,后来再也没有成功过,因为它很神奇,如果可以找一个替代request.json吧。