信息发布→ 登录 注册 退出

详解Python flask的前后端交互

发布时间:2026-01-11

点击量:
目录
  • 前端
    • index.html
    • script.js
  • 后端
    • app.py
  • 总结

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

    按下按钮之前:

    按下按钮之后:

    代码结构

    这是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

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

    总结

    本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!

    在线客服
    服务热线

    服务热线

    4008888355

    微信咨询
    二维码
    返回顶部
    ×二维码

    截屏,微信识别二维码

    打开微信

    微信号已复制,请打开微信添加咨询详情!