脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 详解Python flask的前后端交互

详解Python flask的前后端交互

2022-11-20 12:06_APTX4869 Python

这篇文章主要为大家详细介绍了Python flask的前后端交互,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

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

按下按钮之前:

详解Python flask的前后端交互

按下按钮之后:

详解Python flask的前后端交互

代码结构

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

详解Python flask的前后端交互

前端

index.html

很简单的一个select下拉选框,一个按钮和一个文本,这里的 {{ temp }} 是从后端调用的。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<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格式。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

延伸 · 阅读

精彩推荐