詳解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)文章
關(guān)于Python的高級數(shù)據(jù)結(jié)構(gòu)與算法
這篇文章主要介紹了關(guān)于Python的高級數(shù)據(jù)結(jié)構(gòu)與算法,掌握這些數(shù)據(jù)結(jié)構(gòu)和算法將幫助我們在實際編程中解決各種問題,提高我們的編程技巧和水平,需要的朋友可以參考下2023-04-04
Python實現(xiàn)人臉識別并進(jìn)行視頻跟蹤打碼
這篇文章主要為大家詳細(xì)介紹了如何利用Python實現(xiàn)人臉識別并進(jìn)行視頻跟蹤打碼效果,羞羞的畫面統(tǒng)統(tǒng)打上馬賽克,感興趣的小伙伴可以了解一下2023-03-03
Python開發(fā)之QT解決無邊框界面拖動卡屏問題(附帶源碼)
朋友在學(xué)習(xí)QT的過程中,都會遇到各種問題,今天就QT無邊框拖動花屏問題給大家詳細(xì)介紹,究竟該如何解決呢,下面通過實例代碼和圖文相結(jié)合給大家詳細(xì)介紹,需要的朋友參考下吧2021-05-05
50行Python代碼實現(xiàn)視頻中物體顏色識別和跟蹤(必須以紅色為例)
本文通過50行Python代碼實現(xiàn)視頻中物體顏色識別和跟蹤效果,通過實例截圖和實例代碼給大家講解的非常詳細(xì),需要的朋友可以參考下2019-11-11

