javascript - 怎麼從flask中接受從jquery發送的json資料?
漂亮男人
漂亮男人 2017-05-18 11:01:48
0
3
622

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(),同樣行不通。到底是哪裡出錯了,真心求教。

漂亮男人
漂亮男人

全部回覆(3)
小葫芦

找到答案了,只是在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...

Peter_Zhu

jquery的ajax發送data的時候不需要JSON.stringify.他會自動處理.

迷茫

根據你的描述,你的已經把問題找到了,為什麼不繼續嘗試一下,或者看下文檔

@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.
但是使用. : 'Request' object has no attribute 'get_json'

所以我只是成功使用過一次request.json,後來再也沒有成功過,因為它很神奇,如果可以找一個替代request.json吧。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!