久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

javascript - 怎么從flask中接受從jquery發(fā)送的json數(shù)據(jù)?

瀏覽:137日期:2023-10-12 17:12:19

問(wèn)題描述

flask app中從前端接受json的數(shù)據(jù),但是flask的request中并沒(méi)有接受成功,其中沒(méi)有數(shù)據(jù),換了很多函數(shù)都行不通。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中的視圖函數(shù):

@main.route(’/getjson’, methods = [’GET’, ’POST’])def getjson(): a = request.json if a:return jsonify(user = 'Right') return jsonify(user = 'error')

僅僅判斷request.json是不是存在,但是返回來(lái)的總是“error”的字符串。request.json中總是null。后來(lái)?yè)Q了request.args.get(),同樣行不通。到底是哪里出錯(cuò)了,真心求教。

問(wèn)題解答

回答1:

找到答案了,僅僅是在jquery部分出了問(wèn)題。$.ajax的參數(shù)contentType,默認(rèn)是 'application/x-www-form-urlencoded',需要把這個(gè)參數(shù)設(shè)置成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發(fā)送data的時(shí)候不需要JSON.stringify.他會(huì)自動(dòng)處理.

回答3:

根據(jù)你的描述,你的已經(jīng)把問(wèn)題找到了,為什么不繼續(xù)嘗試一下,或者看下文檔

@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’

輸出結(jié)果

None{'id':1}CombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([(’{'id':1}’, u’’)])])

request.json很奇葩,確實(shí)沒(méi)數(shù)據(jù),但是它是可以用的,你這里沒(méi)用的原因如下:

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(),它無(wú)情的報(bào)錯(cuò)說(shuō)AttributeError: ’Request’ object has no attribute ’get_json’

所以我只是成功使用過(guò)一次request.json,后來(lái)再也沒(méi)有成功過(guò),因?yàn)樗苌衿?,如果可以找一個(gè)替代request.json吧。

標(biāo)簽: JavaScript
相關(guān)文章:
主站蜘蛛池模板: 延安市| 三河市| 娄底市| 临海市| 海兴县| 齐齐哈尔市| 淮滨县| 福建省| 韶关市| 松江区| 京山县| 集安市| 南木林县| 蒙阴县| 棋牌| 绥宁县| 油尖旺区| 浦城县| 金平| 静安区| 那曲县| 和田市| 法库县| 濉溪县| 绵竹市| 亚东县| 通榆县| 宿州市| 崇义县| 开化县| 崇礼县| 右玉县| 保定市| 武清区| 商南县| 益阳市| 介休市| 张家界市| 抚远县| 扶风县| 桐城市|