这篇文章主要为大家详细介绍了Python flask的前后端交互,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
场景:按下按钮,将左边的下拉选框内容发送给后端,后端再将返回的结果传给前端显示。
按下按钮之前:
按下按钮之后:
代码结构
这是flask默认的框架(html写在templates文件夹内、css和js写在static文件夹内)
前端
index.html
很简单的一个select下拉选框,一个按钮和一个文本,这里的 {{ temp }}
是从后端调用的。
TEMP {{ temp }}
script.js
这里给按钮添加一个监听事件,按下就会给服务器发送内容,成功了则返回内容并更改display
。
注意
- 需要在html里添加
,否则
$
字符会报错。 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)
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注0133技术站的更多内容!
以上就是详解Python flask的前后端交互的详细内容,更多请关注0133技术站其它相关文章!