詳解Python?flask的前后端交互
場景:按下按鈕,將左邊的下拉選框內(nèi)容發(fā)送給后端,后端再將返回的結果傳給前端顯示。
按下按鈕之前:
按下按鈕之后:
代碼結構
這是flask默認的框架(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">轉換</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)聽事件,按下就會給服務器發(fā)送內(nèi)容,成功了則返回內(nèi)容并更改display
。
注意
- 需要在html里添加
<script src="https://code.jquery.com/jquery-3.6.0.min.js">
,否則$
字符會報錯。 dataType
如果選擇的是json,則前后端交互的內(nèi)容均應為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)
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內(nèi)容!
相關文章
Python實現(xiàn)腳本鎖功能(同時只能執(zhí)行一個腳本)
這篇文章主要介紹了Python實現(xiàn)腳本鎖功能(同時只能執(zhí)行一個腳本),本文給大家分享了兩種方法,大家可以根據(jù)個人所需選擇適合自己的方法2017-05-05python基于concurrent模塊實現(xiàn)多線程
這篇文章主要介紹了python基于concurrent模塊實現(xiàn)多線程,幫助大家更好的理解和學習使用python,感興趣的朋友可以了解下2021-04-04python實現(xiàn)生成字符串大小寫字母和數(shù)字的各種組合
這篇文章主要給大家介紹了關于python生成各種字符串的方法實例,給大家提供些思路,拋磚引玉,希望大家能夠喜歡2019-01-01python實現(xiàn)對excel進行數(shù)據(jù)剔除操作實例
python在數(shù)據(jù)分析這方便的介紹應該不用多說了,下面這篇文章主要給大家介紹了關于利用python實現(xiàn)對excel進行數(shù)據(jù)剔除操作的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。2017-12-12