[Flask] Server Data를 Client로 불러오기

Yewon Kim·2020년 6월 23일
0

Flask

목록 보기
3/3

DB의 모든 data를 찾아 json 형태로 client에 return

📄app.py

@app.route('/api/showarticles', methods=['GET'])
def show_articles():
    articles = list(db.articles.find({},{'_id':0}))
    return jsonify({'result':'success', 'articles': articles})

return 받은 data를 html 형태로 만들어주는 JavaScript 함수 작성

📄common.js

function make_article(category_code, article_body) {
    let temp_html = `
	<article>
	  <a href='#'>${category_code}</a>
	  <h3>${post_body}</h3>
	</article>`
    return temp_html;
}

return 받은 data를 client에 보여주는 ajax 함수 작성

📄common.js

function show_article() {
    $('#articleBox').empty();

    $.ajax({
        type: "GET",
        url: "/api/top",
        data: {},
        success: function (response) {
          let articles = response['articles_list']
          for (let i = 0; i < articles.length; i++) {
            let article = articles[i];

            let code = article['category_code'];
            let body = article['article_body'];
            
            let append_one = make_article(code, body);
            
            $('#articleBox').append(append_one);
        }
    });
}

html 내에 data를 보여줄 영역 설정

📄index.html 문서 body에 articleBox라는 id값을 가진 영역을 만들어준다.

<body>
    <div id="postingBox">...

    <div id="articleBox"></div>
</body>

Server 로딩과 동시에 show_article()를 호출하는 script 작성

📄index.html 문서 head에 다음 script를 추가해준다.

<script>
    $(document).ready(function () {
        show_article();
    });
</script>

이제 app.py를 구동하고 Chrome에서 http://localhost:5000/ 에 접속해 보면, 작성했던 data가 #articleBox 내에서 표시되는 것을 볼 수 있다.

profile
산업의 안팎에서 투자의 원칙을 배우고 싶은 학생입니다.

0개의 댓글