Python 如何从 AJAX 帖子获取 Flask 中的数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37631388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to GET data in Flask from AJAX post
提问by 0248881
I want to retrieve the data from the variable 'clicked' so I can use it in SQL queries in Flask.
我想从变量“clicked”中检索数据,以便我可以在 Flask 的 SQL 查询中使用它。
JQuery
查询
$(document).ready(function(){
var clicked;
$(".favorite").click(function(){
clicked = $(this).attr("name");
$.ajax({
type : 'POST',
url : "{{url_for('test')}}",
data : clicked
});
});
});
Flask/Python
烧瓶/Python
@app.route('/test/', methods=['GET','POST'])
def test():
return render_template('test.html')
回答by Sugam
You can compose your payload in your ajax request as so:
您可以在 ajax 请求中编写有效负载,如下所示:
$(document).ready(function(){
var clicked;
$(".favorite").click(function(){
clicked = $(this).attr("name");
$.ajax({
type : 'POST',
url : "{{url_for('test')}}",
contentType: 'application/json;charset=UTF-8',
data : {'data':clicked}
});
});
});
In your flask endpoint, you can extract the value as follows:
在您的烧瓶端点中,您可以按如下方式提取值:
@app.route('/test/', methods=['GET','POST'])
def test():
clicked=None
if request.method == "POST":
clicked=request.json['data']
return render_template('test.html')
回答by ASSILI Taher
I used the best answer but i found a bad request error. I solve this error as below:
我使用了最好的答案,但我发现了一个错误的请求错误。我解决这个错误如下:
1- remove this line from ajax request:
1- 从 ajax 请求中删除这一行:
contentType: 'application/json;charset=UTF-8',
2- Access to data by request.form instead of request.json.
2- 通过 request.form 而不是 request.json 访问数据。
The Javascript part will similar to this:
Javascript 部分将类似于:
$(document).ready(function(){
var clicked;
$(".favorite").click(function(){
clicked = $(this).attr("name");
$.ajax({
type : 'POST',
url : "{{url_for('test')}}",
data : {'data':clicked}
});
});
});
Flask part:
烧瓶部分:
@app.route('/test/', methods=['GET','POST'])
def test():
clicked=None
if request.method == "POST":
clicked=request.form['data']
return render_template('test.html')
回答by yardstick17
At your flask app end-point , you can define method to retrieve GET/POST data like this :
在您的烧瓶应用程序端点,您可以定义方法来检索 GET/POST 数据,如下所示:
from flask_restful import reqparse
def parse_arg_from_requests(arg, **kwargs):
parse = reqparse.RequestParser()
parse.add_argument(arg, **kwargs)
args = parse.parse_args()
return args[arg]
@app.route('/test/', methods=['GET','POST'])
def test():
clicked = parse_arg_from_requests('data')
return render_template('test.html' , clicked=clicked)