Python 官方文档:入门教程 => 点击学习
AxiOS 是一个基于promise的Http库,该库是一个更好的替代ajax向后端发送数据或请求数据的前端组件库,其本质上也是对原生XHR的封装,只不过它是Promise的实现版本
AxiOS 是一个基于promise的Http库,该库是一个更好的替代ajax向后端发送数据或请求数据的前端组件库,其本质上也是对原生XHR的封装,只不过它是Promise的实现版本,符合最新的ES规范,如下案例运用axios向后端提交JSON字符串,后端通过flask响应请求并处理。
前端运用Axios发送数据的两种方式。
<html>
<head>
<meta charset="UTF-8">
<title>LyShark</title>
<script src="https://cdn.lyshark.com/javascript/axios/0.26.0/axios.min.js"></script>
</head>
<body>
<input type="text" name="name" id="name" />
<input type="text" name="age" id="age" />
<button onclick="saveHanderPost()" >提交</button>
</body>
<!-- 第一种发送方法 -->
<script type="text/javascript">
function saveHanderPost()
{
let name = document.getElementById("name").value;
let age = document.getElementById("age").value;
axios.post("/",{
name:name,
age:age
})
.then(function(response){
console.log(response);
console.log(response.data.username);
console.log(response.data.message);
})
.catch(function(error){
console.log(error);
})
}
</script>
<!-- 第二种发送方法 -->
<script type="text/javascript">
function saveHanderPostB()
{
let name = document.getElementById("name").value;
let age = document.getElementById("age").value;
axios({
url: "/",
method: "post",
data: {
name: name,
age:age
},
responseType: "text/json",
})
.then(function(response){
console.log(response);
console.log(response.data.username);
console.log(response.data.message);
})
.catch(function(error){
console.log(error);
})
}
</script>
</html>
python后端使用Flask接收并处理前端发送过来的JSON字符串。
from flask import Flask,render_template,request
import json
app = Flask(import_name=__name__,
static_url_path='/Python', # 配置静态文件的访问url前缀
static_folder='static', # 配置静态文件的文件夹
template_folder='templates') # 配置模板文件的文件夹
@app.route('/', methods=["GET","POST"])
def index():
if request.method == "GET":
return render_template("index.html")
elif request.method == "POST":
val = request.get_json()
print("收到用户: {} ---> 年龄: {}".fORMat(val["name"],val["age"]))
# 返回JSON类型
return json.dumps({"username": "lyshark","message": "hello lyshark"})
if __name__ == '__main__':
app.run(host="127.0.0.1", port=80, debug=False)
运行后提交数据前后端均可接收到数据:
到此这篇关于Flask框架运用Axios库实现前后端交互详解的文章就介绍到这了,更多相关Flask Axios前后端交互内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Flask框架运用Axios库实现前后端交互详解
本文链接: https://www.lsjlt.com/news/175595.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