YOGYUI

Flask - Dynamic Page Update (Ajax) 본문

Software/Python

Flask - Dynamic Page Update (Ajax)

요겨 2021. 1. 10. 23:58
반응형

Ajax (Asynchronous JavaScript and XML)

 

Ajax - 위키백과, 우리 모두의 백과사전

위키백과, 우리 모두의 백과사전. 다른 뜻에 대해서는 에이젝스 문서를 참조하십시오. 다른 뜻에 대해서는 아이아스 문서를 참조하십시오. Ajax(Asynchronous JavaScript and XML, 에이잭스)는 비동기적인

ko.wikipedia.org

 

Flask 자체의 기술적 내용에 해당하는 포스팅은 아니다

Ajax 사용에 대한 예시 (page update에 대한 요청은 페이지가 수행하고, 서버는 라우팅만 잘 구현해주면 된다)

 

[Structure]

+ proj

    + templates

        - index.html

    - app.py

 

index.html에서 1초에 한번씩 update POST 호출하여 현재 시간을 서버로부터 문자열로 받아 동적으로 업데이트 (page refresh 없이) 하는 코드를 구현해보자

<!-- index.html -->
<!DOCTYPE html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <a>Current Time</a>
    <h1 id="time"></h1>
    <script>
        setInterval(function(){$.ajax({
            url: '/update',
            type: 'POST',
            success: function(response) {
                console.log(response);
                $("#time").html(response["time"]);
            },
            error: function(error) {
                console.log(error);
            }
        })}, 1000);
    </script>
</body>
# app.py
import datetime
from flask import Flask, render_template, jsonify

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/update', methods=['POST'])
def update():
    now = datetime.datetime.now()
    return jsonify({
        'time': now.strftime('%Y-%d-%m %H:%M:%S'),
    })

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=9999, debug=True)

크롬에서 127.0.0.1:9999로 접속하니 잘 동작한다 (브라우저 콘솔 로그 및 파이참 콘솔 로그 확인)

크롬
pycharm

 

참고:

stackoverflow.com/questions/62150925/how-do-i-update-values-without-refreshing-the-page-on-my-flask-project

stackoverflow.com/questions/59780007/ajax-with-flask-for-real-time-esque-updates-of-sensor-data-on-webpage

stackoverflow.com/questions/40963401/flask-dynamic-data-update-without-reload-page/40964086

반응형
Comments