[英]Issue with sending data to python flask from AJAX
I am not able to retrieve data field of AJAX in python flask.我无法在 python flask 中检索 AJAX 的数据字段。 Its shows type error when I try to retrieve data.
当我尝试检索数据时,它显示类型错误。
type
and forwho
are of array type. type
和forwho
是数组类型。 When I alert them in AJAX it works.当我在 AJAX 中提醒他们时,它可以工作。 Here is my code,
这是我的代码,
// Ajax
$.ajax({
url: '/products',
data: JSON.stringify({'type':type,'forwho': forwho}),
contentType: "application/json; charset=utf-8",
type: 'POST',
success: function(response){
/*alert("success");*/
$("#content").html(response);
},
error: function(error){
/*alert("error");*/
console.log(error);
}
});
# app.py
@app.route('/products', methods =['POST', 'GET'])
def all_products():
if request.method == 'POST':
print("inside all products post")
type = json.loads(request.form.get('type'))
forwho = json.loads(request.form.getlist('forwho'))
print(type)
print(forwho)
when I print print(request.args.get('typearr')) in all_products() it returns None当我在 all_products() 中打印 print(request.args.get('typearr')) 它返回 None
type =request.json['type']
forwho = request.json['forwho']
Flask automatically parses JSON when having application/JSON in your request.当您的请求中有应用程序/JSON 时,Flask 会自动解析 JSON。
This solution finally worked for me.这个解决方案终于对我有用。
ajax: ajax:
data: JSON.stringify({'typearr':type,'forwho':forwho})
``````````````````
app.py:
#import ast
``````````````
data = request.get_data()
data = ast.literal_eval(data.decode("UTF-8"))
typearr = data['typearr']
forwho = data['forwho']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.