我想使用jQuery将JSON数据发送到Flask路由。但是,request.get_json()
会出错。为什么这不起作用?
my_array = {"student_data":{"actual_data":12,"sheet_data":23,"age":"20"},"teacher_data":{"actual_data":193,"sheet_data":203,"age":"40"},"school_data":{"actual_data":593,"sheet_data":29,"age":"49"}};
$.ajax({
url: '/submit_method',
data: my_array,
contentType: 'application/json; charset=utf-8',
type : 'GET',
async: 'false',
success: function (serverResponse) {
}
});
@app.route('/submit_method', methods=['GET'])
def submit_method():
k = request.get_json()
return ''
答案 0 :(得分:0)
您必须使用POST方法而不是GET。
@app.route('/submit_method', methods=['POST'])
def submit_method():
k = request.data # gets request body in form of dictionary
return json.dumps(k) # converts dictionary to json
$.ajax({
url: '/submit_method', data: JSON.stringify(my_array),
contentType:"application/json; charset=utf-8",
type : 'POST', async: "false", success : function (serverResponse) {}});
答案 1 :(得分:0)
问题是必须首先使用 JSON.stringify 将JavaScript转换为JSON字符串。否则,Flask将不会将其视为application / json内容类型,并拒绝请求400。
$.ajax({
url: '/submit_method',
data: JSON.stringify(my_array),
contentType: 'application/json; charset=utf-8',
type : 'GET',
async: 'false',
success: function (serverResponse) {
}
});