Python

[Python] AJAX / fetch / axios

아잠만_ 2024. 7. 9. 12:22

myflask.py

from flask import Flask, redirect
from flask.json import jsonify
from flask.globals import request

app = Flask(__name__)

@app.route('/')
def main():
    return redirect('/static/ajax.html')

@app.route('/hello.ajax', methods=['POST'])
def ajax_hello():
    menu = request.form['menu']
    # json형태로 정보 보내기
    print("menu", menu)
    return jsonify({"message":"ok"})

@app.route('/fetch.ajax', methods=['POST'])
def ajax_fetch():
    menu = request.get_json()['menu']
    # json형태로 정보 보내기
    print("menu", menu)
    return jsonify({"message":"ok"})

@app.route('/axios.ajax', methods=['POST'])
def ajax_axios():
    menu = request.get_json()['menu']
    # json형태로 정보 보내기
    print("menu", menu)
    return jsonify({"message":"ok"})

if __name__ == '__main__':
    # app.run(debug=True)
    app.run(host="0.0.0.0", port=80, debug=True)

ajax.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="./jquery-3.7.1.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
function fn_ajax(){
	// ajax_hello로 이동 (동기식)
/* 	location.href="/ajax_hello"; */

$.ajax({
	url : "/hello.ajax",
	type : "POST",
	data : { menu : "짬뽕" },
	success : function(res){
		console.log(res);
		console.log(res.message);
	}
})
}

function fn_fetch(){
	fetch('/fetch.ajax', {
		method : "POST",
		headers: {
		    'Content-Type': 'application/json'
		  },
		 body: JSON.stringify({"menu":"짬뽕"})
	})
	.then(function(response){
		console.log(response);
		return response.json();
	})
	.then(function(res){
		console.log(res);
		console.log(res.message);
	})
}

function fn_axios(){
	axios.post('/axios.ajax', {menu:"짬뽕"}).then(function(res){
		console.log(res.data)
	});
}
</script>
</head>
<body>
<a href="javascript:fn_ajax()">ajax</a>
<a href="javascript:fn_fetch()">fetch</a>
<a href="javascript:fn_axios()">axios</a>
</body>
</html>