Decode JSON in flask

若如初见. 提交于 2021-01-29 10:31:03

问题


i want to send JSON format data in my flask app using AJAX call, when i send it i got "None" in flask.

here is jquery,

$('#form').on('click',function(){
  var text = $('#textField').val();
  var obj = {name:text};
  var myJSON = JSON.stringify(obj);
  $.ajax({
    data : myJSON,
    url: '/process',
    type : 'post',
    contentType: 'application/json',
    dataType : 'json'
  })
})

here is my Flask route,

@app.route('/process',methods=["POST"])
def process():
    data = request.json
    return render_template("form.html",data = data)

in data i got "None".


回答1:


  • return render_template is not fruitful as data is being sent via Ajax. It will return the template contents.
  • You can receive the data returned from Flask via done method in Ajax.

I am adding an example code to demonstrate how to handle Ajax submission with JSON data.

app.py:

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route('/process',methods=["GET", "POST"])
def process():
    if request.method == 'POST':
        data = request.json
        return jsonify(data)
    return render_template("form.html")

app.run(debug=True)

form.html:

<html>
    <head>
        <title>Form</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
        <div id="data"></div>

        <input type="text" id="textField" />
        <button id="demo_btn">Dummy button</button>
        <script>
            $(document).ready(function () {
                $("#demo_btn").on("click", function() {
                    var text = $('#textField').val();
                    var obj = {name:text};
                    var myJSON = JSON.stringify(obj);
                    $.ajax({                        
                        url: '/process',
                        type : 'post',
                        contentType: 'application/json',
                        dataType : 'json',
                        data : myJSON
                    }).done(function(result) {
                        $("#data").html(result["name"]);
                    }).fail(function(jqXHR, textStatus, errorThrown) {
                        console.log("fail: ",textStatus, errorThrown);
                    });
                });
            });
        </script>       
    </body>
</html>

Output:

Reference:

http://api.jquery.com/jquery.ajax/




回答2:


It looks like JQuery isn't setting the correct header.

If you use the request.get_json() method instead of the request.json property it will get json irrespective of the header.



来源:https://stackoverflow.com/questions/53502324/decode-json-in-flask

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!