search

Home  >  Q&A  >  body text

javascript - How to accept json data sent from jquery from flask?

The flask app accepts json data from the front end, but the flask request does not accept it successfully. There is no data in it, and it does not work after changing many functions.
js code

$(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)
            }
        });
    });
});

View functions in flask:

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

Only determines whether request.json exists, but the string returned is always "error". There is always null in request.json. Later, I changed request.args.get(), but it also didn't work. Where did I go wrong? I sincerely ask for advice.

漂亮男人漂亮男人2755 days ago659

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-05-18 11:03:48

    I found the answer, it was just a problem with the jquery part. The parameter contentType of $.ajax defaults to "application/x-www-form-urlencoded". You need to set this parameter to 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)
            }
        });

    Reference: https://flask.readthedocs.io/...
    http://stackoverflow.com/ques...

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-18 11:03:48

    jquery’s ajax does not require JSON.stringify when sending data. It will be processed automatically.

    reply
    0
  • 迷茫

    迷茫2017-05-18 11:03:48

    According to your description, you have found the problem, why not continue to try it, or read the documentation

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

    Output results

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

    request.json is very strange. It really has no data, but it can be used. The reason why it is not useful here is as follows:

    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.
    But when I use get_json(), it ruthlessly reports an AttributeError : 'Request' object has no attribute 'get_json'

    So I only successfully used request.json once, and then never succeeded again, because it is magical, if I can find an alternative to request.json.

    reply
    0
  • Cancelreply