Python 官方文档:入门教程 => 点击学习
目录前端index.htmlscript.js后端app.py总结场景:按下按钮,将左边的下拉选框内容发送给后端,后端再将返回的结果传给前端显示。 按下按钮之前: 按下按钮之后:
场景:按下按钮,将左边的下拉选框内容发送给后端,后端再将返回的结果传给前端显示。
按下按钮之前:
按下按钮之后:
代码结构
这是flask默认的框架(html写在templates文件夹内、CSS和js写在static文件夹内)
很简单的一个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>
这里给按钮添加一个监听事件,按下就会给服务器发送内容,成功了则返回内容并更改display
。
注意
<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);
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)
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!
--结束END--
本文标题: 详解Python flask的前后端交互
本文链接: https://www.lsjlt.com/news/144595.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0