반응형
AJAX post에서 Flask에 데이터를 가져오는 방법
Flask에서 SQL 쿼리에 사용할 수 있도록 'clicked' 변수에서 데이터를 검색하고 싶습니다.
제이쿼리
$(document).ready(function(){
var clicked;
$(".favorite").click(function(){
clicked = $(this).attr("name");
$.ajax({
type : 'POST',
url : "{{url_for('test')}}",
data : clicked
});
});
});
플라스크/피톤
@app.route('/test/', methods=['GET','POST'])
def test():
return render_template('test.html')
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}
});
});
});
플라스크 끝점에서 다음과 같이 값을 추출할 수 있습니다.
@app.route('/test/', methods=['GET','POST'])
def test():
clicked=None
if request.method == "POST":
clicked=request.json['data']
return render_template('test.html')
최선의 답변을 사용했지만 잘못된 요청 오류를 발견했습니다.다음과 같이 이 오류를 해결합니다.
1- ajax 요청에서 이 행을 제거합니다.
contentType: 'application/json;charset=UTF-8',
2- 요청에 의한 데이터 접근.request.json 대신 폼을 만듭니다.
자바스크립트 부분은 이와 유사합니다.
$(document).ready(function(){
var clicked;
$(".favorite").click(function(){
clicked = $(this).attr("name");
$.ajax({
type : 'POST',
url : "{{url_for('test')}}",
data : {'data':clicked}
});
});
});
플라스크 부품:
@app.route('/test/', methods=['GET','POST'])
def test():
clicked=None
if request.method == "POST":
clicked=request.form['data']
return render_template('test.html')
플라스크 추가 지점에서 다음과 같이 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)
언급URL : https://stackoverflow.com/questions/37631388/how-to-get-data-in-flask-from-ajax-post
반응형
'programing' 카테고리의 다른 글
avg 및 그룹을 사용한 SQL 쿼리 (0) | 2023.10.19 |
---|---|
MariaDB 시퀀스가 음수를 생성하는 이유는 무엇입니까? (0) | 2023.10.19 |
테이블을 분할하기에 좋은 크기(행 수)는 무엇입니까? (0) | 2023.10.19 |
표에서 값이 연속적으로 발생한 횟수 (0) | 2023.10.19 |
CSS를 사용한 대체 테이블 행 색상? (0) | 2023.10.19 |