问题
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