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.
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.
Reference: https://flask.readthedocs.io/...
http://stackoverflow.com/ques...
jquery’s ajax does not require JSON.stringify when sending data. It will be processed automatically.
According to your description, you have found the problem, why not continue to try it, or read the documentation
Output results
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:
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.