프로그래밍/Flask

ajax 사용하기(json data 보내고 받기)

Gooding 2021. 1. 4. 16:11
728x90
반응형

Flask에서 ajax 사용하기

1️⃣ data를 JSON.stringify(data)로 보내기

$.ajax({
	type : 'POST',                                  
	url : 'http://127.0.0.1:5000/report',
	data : JSON.stringify(word),
	dataType : 'JSON',
	success : function(result){
		$(".about--banner").append(result)
	},
	error : function(xtr,status,error){
		alert(xtr +":"+status+":"+error);
	}
});

 

2️⃣ jsonify import하기

3️⃣ request.get_json("data")로 데이터 받기

4️⃣ jsonify()로 데이터 보내기

from flask import Flask, render_template, request, redirect, send_file, jsonify

@app.route("/report", methods =['POST'])
def report():
    word = request.get_json("word")  #json data를 가져오기
    if word:
        word = word.lower()
        existingNews = db.get(word)
        if existingNews:
            news = existingNews
        else:
            news = get_news(word)
            db[word] = news
    else:  # 검색어를 입력하지 않은 경우 redirect시키기
        return redirect("/")  
    return jsonify(render_template(
        "report.html", 
        searchingBy=word, 
        resultNumber=len(news),
        news=news
    ))
반응형

'프로그래밍 > Flask' 카테고리의 다른 글

Ajax의 페이징 처리  (0) 2021.01.06
페이지네이션  (0) 2021.01.05
Web Scraping9(CSV파일에 저장하고 다운로드)  (0) 2021.01.01
Web Scraping8(검색 결과 페이지에 출력하기)  (0) 2021.01.01
html include 하기  (0) 2020.12.31