如何从AJAX帖子中获取Flask中的数据

时间:2022-10-18 07:41:59

I want to retrieve the data from the variable 'clicked' so I can use it in SQL queries in Flask.

我想从变量'clicked'中检索数据,这样我就可以在Flask的SQL查询中使用它。

JQuery

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')

2 个解决方案

#1


4  

you can compose your payload in your ajax request as

您可以在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')

#2


0  

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)

#1


4  

you can compose your payload in your ajax request as

您可以在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')

#2


0  

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)