javascript - 怎么从flask中接受从jquery发送的json数据?
问题描述
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.uservar 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(),同样行不通。到底是哪里出错了,真心求教。
问题解答
回答1:找到答案了,仅仅是在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...
回答2:jquery的ajax发送data的时候不需要JSON.stringify.他会自动处理.
回答3:根据你的描述,你的已经把问题找到了,为什么不继续尝试一下,或者看下文档
@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 parsedJSON data. Otherwise this will be None. The get_json() method shouldbe used instead.但是我使用get_json(),它无情的报错说AttributeError: ’Request’ object has no attribute ’get_json’
所以我只是成功使用过一次request.json,后来再也没有成功过,因为它很神奇,如果可以找一个替代request.json吧。
相关文章:
1. mysql - 测试不同sql语句的查询效率2. MySQL 如何 SELECT 除去某一列的所有列?3. mysql 插入数值到特定的列一直失败4. python - scrapy 如何组合2个不同页面的数据,一并存储5. mysql - 是用火车头采集器,采集后发布到数据库,提示如下,求解!!!6. mysql计算附近的地铁站7. html5 - 有什么好的方法防止微信公众号发红包被刷么?8. html - python制作下拉列表,怎样引用一个json文档里面的数据来实现。9. python2.7 - python 函数或者类 代码的执行顺序10. python小白 问关于递归的问题

网公网安备