国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

javascript - 怎么從flask中接受從jquery發送的json數據?

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

問題描述

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吧。

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 宣汉县| 陆丰市| 丽水市| 罗源县| 临西县| 定西市| 河北省| 神木县| 连平县| 利辛县| 嘉义市| 廉江市| 资阳市| 南溪县| 万州区| 信丰县| 鸡泽县| 凤山县| 阜宁县| 拜城县| 永寿县| 工布江达县| 本溪市| 九江市| 大余县| 漳州市| 达孜县| 武定县| 正阳县| 枝江市| 定襄县| 长丰县| 淅川县| 中方县| 南陵县| 乌苏市| 闻喜县| 华坪县| 乌兰察布市| 玛沁县| 西贡区|