网络编程
位置:首页>> 网络编程>> Python编程>> 详解Python flask的前后端交互

详解Python flask的前后端交互

作者:_APTX4869  发布时间:2023-03-19 06:41:05 

标签:Python,flask,前后端交互

场景:按下按钮,将左边的下拉选框内容发送给后端,后端再将返回的结果传给前端显示。

按下按钮之前:

详解Python flask的前后端交互

按下按钮之后:

详解Python flask的前后端交互

代码结构

这是flask默认的框架(html写在templates文件夹内、css和js写在static文件夹内)

详解Python flask的前后端交互

前端

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

这里给按钮添加一个监听事件,按下就会给服务器发送内容,成功了则返回内容并更改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)

来源:https://blog.csdn.net/nanke_4869/article/details/123850333

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com