Flask 通过Axios库前后端交互

本文展示了如何使用前端库Axios向后端发送POST请求,以JSON格式传递数据。前端通过获取表单输入,利用Axios两种不同的调用方式提交数据到Flask应用。后端接收到数据后进行处理,并返回JSON响应。这个过程涉及到Promise的使用和Flask的路由及请求处理。

Axios 是一个基于promise的HTTP库,该库是一个更好的替代ajax向后端发送数据或请求数据的前端组件库,其本质上也是对原生XHR的封装,只不过它是Promise的实现版本,符合最新的ES规范,如下案例运用axios向后端提交JSON字符串,后端通过Flask响应请求并处理。

前端发送数据的第一种方式。

<head>
    <script src="https://www.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>

<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 saveHanderPost()
    {
        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>

Python后端使用Flask接收并处理前端发送过来的JSON字符串。

from flask import Flask
from flask import render_template,request
import json

app = Flask(__name__)

@app.route('/',methods=['GET','POST'])
def hello_world():
    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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王瑞MVP

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值