我尝试将json数据从JavaScript发送到flaskapp。但是烧瓶不接受从JavaScript发送的json数据,请求为空,哪里出错了?
这是我的烧瓶代码。
public JsonResult IsPatnikExists(string firstname, string lastname)
{
return Json(!db.tbl_patnici.Any(x => x.firstname == firstname) && !db.tbl_patnici.Any(x => x.lastname == lastname), JsonRequestBehavior.AllowGet);
}
这是我的javascript代码。
@main.route('/getjson', methods = ['GET', 'POST'])
def getjson():
a = request.json
return jsonify(user = a)
页面上返回的数据始终为null。 Request.arg.get也不起作用。
答案 0 :(得分:0)
Flask的request.json
默认需要application/json
内容类型,但$.ajax
设置application/x-www-form-urlencoded
。在发出请求时设置内容类型。
$.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)
}
});
或者,发送对象本身,而不是JSON.stringify()
:
$.ajax({
url: "{{ url_for('main.getjson') }}",
type: "POST",
data: {
n1: "test1",
n2: "test2",
n3: "test3"
},
dataType: "json",
success: function(data){
var a = data.user
var texthtml = "<p>" + a + "</p>"
$("#result").html(texthtml)
}
});
这将以表格编码方式发送数据,因此您可以使用Flask中的request.form
来阅读它。
dataType
是您希望从服务器接收的数据类型,而contentType
是您发送到服务器的数据类型。
请参阅: