詳解Python?flask的前后端交互
場景:按下按鈕,將左邊的下拉選框內(nèi)容發(fā)送給后端,后端再將返回的結(jié)果傳給前端顯示。
按下按鈕之前:

按下按鈕之后:

代碼結(jié)構(gòu)
這是flask默認(rèn)的框架(html寫在templates文件夾內(nèi)、css和js寫在static文件夾內(nèi))

前端
index.html
很簡單的一個select下拉選框,一個按鈕和一個文本,這里的 {{ temp }} 是從后端調(diào)用的。
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="static/css/style.css">
<title>TEMP</title>
</head>
<body>
<div class="container">
<div class="person">
<select id="person-one">
<option value="新一">新一</option>
<option value="小蘭">小蘭</option>
<option value="柯南">柯南</option>
<option value="小哀">小哀</option>
</select>
</div>
<div class="transfer">
<button class="btn" id="swap">轉(zhuǎn)換</button>
</div>
<p id="display">{{ temp }}</p>
</div>
<script src="/static/js/script.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>
</html>
script.js
這里給按鈕添加一個監(jiān)聽事件,按下就會給服務(wù)器發(fā)送內(nèi)容,成功了則返回內(nèi)容并更改display。
注意
- 需要在html里添加
<script src="https://code.jquery.com/jquery-3.6.0.min.js">,否則$字符會報錯。 dataType如果選擇的是json,則前后端交互的內(nèi)容均應(yīng)為json格式。
const person = document.getElementById('person-one');
const swap = document.getElementById('swap');
function printPerson() {
$.ajax({
type: "POST",
url: "/index",
dataType: "json",
data:{"person": person.value},
success: function(msg)
{
console.log(msg);
$("#display").text(msg.person);//注意顯示的內(nèi)容
},
error: function (xhr, status, error) {
console.log(error);
}
});
}
swap.addEventListener('click', printPerson);
后端
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
@app.route("/index", methods=['GET', 'POST'])
def index():
message = "選擇的人物為:"
if request.method == 'POST':
person = str(request.values.get("person"))
return {'person': person}
return render_template("index.html", temp=message)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8987, debug=True)
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Python實現(xiàn)腳本鎖功能(同時只能執(zhí)行一個腳本)
這篇文章主要介紹了Python實現(xiàn)腳本鎖功能(同時只能執(zhí)行一個腳本),本文給大家分享了兩種方法,大家可以根據(jù)個人所需選擇適合自己的方法2017-05-05
淺談python裝飾器探究與參數(shù)的領(lǐng)取
下面小編就為大家分享一篇淺談python裝飾器探究與參數(shù)的領(lǐng)取,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12
python基于concurrent模塊實現(xiàn)多線程
這篇文章主要介紹了python基于concurrent模塊實現(xiàn)多線程,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-04-04
python實現(xiàn)生成字符串大小寫字母和數(shù)字的各種組合
這篇文章主要給大家介紹了關(guān)于python生成各種字符串的方法實例,給大家提供些思路,拋磚引玉,希望大家能夠喜歡2019-01-01
python實現(xiàn)對excel進(jìn)行數(shù)據(jù)剔除操作實例
python在數(shù)據(jù)分析這方便的介紹應(yīng)該不用多說了,下面這篇文章主要給大家介紹了關(guān)于利用python實現(xiàn)對excel進(jìn)行數(shù)據(jù)剔除操作的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來一起看看吧。2017-12-12

