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. angular.js - protractor初学 参考案例运行测试文件 报Error: Timeout2. android - 如何缩小APK的体积3. angular.js - angular post的Content-Type被设置,导致不能上传图片,求助!!4. javascript - 奇怪的Symbol的问题5. javascript - 在vue-cli引入vux后 使用报错6. css - 移动端 盒子内加overflow-y:scroll后 字体会变大7. javascript - JS new Date() 保存到 mongodb 中会早8个小时,我们这里是东八区,mongodb 保存的是格林尼治时间8. docker安装后出现Cannot connect to the Docker daemon.9. position:absolute、float、display:inline-block 都能实现相同效果,区别是什么?10. html - iframe嵌套网页在iPhone端的显示问题

网公网安备