詳解Python?flask的前后端交互
更新時間:2022年03月31日 11:23:15 作者:_APTX4869
這篇文章主要為大家詳細介紹了Python?flask的前后端交互,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
場景:按下按鈕,將左邊的下拉選框內容發(fā)送給后端,后端再將返回的結果傳給前端顯示。
按下按鈕之前:
按下按鈕之后:
代碼結構
這是flask默認的框架(html寫在templates文件夾內、css和js寫在static文件夾內)
前端
index.html
很簡單的一個select下拉選框,一個按鈕和一個文本,這里的 {{ temp }}
是從后端調用的。
<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ā)送內容,成功了則返回內容并更改display
。
注意
- 需要在html里添加
<script src="https://code.jquery.com/jquery-3.6.0.min.js">
,否則$
字符會報錯。 dataType
如果選擇的是json,則前后端交互的內容均應為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);//注意顯示的內容 }, 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)
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
相關文章
Python實現腳本鎖功能(同時只能執(zhí)行一個腳本)
這篇文章主要介紹了Python實現腳本鎖功能(同時只能執(zhí)行一個腳本),本文給大家分享了兩種方法,大家可以根據個人所需選擇適合自己的方法2017-05-05