【flask】 前后端通信方式 原生js的ajax,总结

前端接收参数

python 复制代码
#如果是路径参数如:/auth/<email>
#渲染模版并向html页面传参数
@app.route('/blog/<blog_id>')
def blog_detail(blog_id):
    return render_template('blog_detail.html',blog_id=blog_id)
    
#如果 methods是post说明参数在请求体里面,
request.form['参数key'] 
Request.form.get['key']

#如果 methods 是get 说明参数在url路径里面
request.args.get('key')
request.values.get('key')

例子是前端需要给邮箱发送验证码。所以需要填写邮箱,然后点击按钮,发送验证码给所填写的邮箱。

前段传递给后段数据(ajax)

这里的例子是js的ajax,js部分逻辑:

首先是获取到按钮,给按钮添加点击事件。点击事件内部逻辑为获取到邮箱输入框中所输入的邮箱,并将其传递给后端。

js中的ajax如果要传递参数,如果是get参数直接在url后面填写即可;如果是post参数,需要在xhr.send()方法后面添加所要传递的参数。参数之间用'&'连接

python 复制代码
#发送post参数
xhr.send("email="+email+"&username="+username);

整体js代码

python 复制代码
window.onload=function(){
    var getVerificationCodeButton = document.getElementById("captcha-btn");
    getVerificationCodeButton.addEventListener('click',function(){
        var inputElement = document.getElementById("exampleInputEmail1");
        var email = inputElement.value;
        //1.创建对象
        const xhr = new XMLHttpRequest();
        //2.初始化xhr对象
        xhr.open('POST','/auth/sendVerificationCode');
        //设置请求头
        xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded'); //固定语法
        //3.发送请求,在这里,可以传请求体参数
        xhr.send("email="+email);
        //4.事件绑定 处理服务器端返回的结果
        //on when
        //readystate是xhr对象中的属性,表示状态
        //0未初始化,刚开始
        //1表示open调用完毕,2表示send方法调用完毕
        //3表示服务端返回部分结果,4表示返回全部结果
        xhr.onreadystatechange = function(){
            //判断服务器已经返回了所有结果
            if(xhr.readyState === 4){
                if(xhr.status >= 200 && xhr.status<300){
                    //处理结果 行 头 空行 体
                    console.log(xhr.status);//响应状态码
                    console.log(xhr.statusText);//状态字符串
                    console.log(xhr.getAllResponseHeaders);//所有响应头
                    console.log(xhr.response);//响应体
                }
            }
        }
    })
}

后端接收参数代码

python 复制代码
#发送验证码到邮箱 ---这个auth是使用蓝图的哦
@auth.route("/sendVerificationCode",methods=["POST","GET"])
def send_verification_code():
    email = request.form.get("email")
    print(email)
    message = Message(subject="发送验证码测试", recipients=[email], body="邮箱发送验证码测试");
    mail.send(message);
    return "发送验证码"
相关推荐
寻星探路8 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
想用offer打牌9 小时前
MCP (Model Context Protocol) 技术理解 - 第二篇
后端·aigc·mcp
KYGALYX10 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了10 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
ValhallaCoder10 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
爬山算法11 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
猫头虎11 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
Moment11 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
八零后琐话12 小时前
干货:程序员必备性能分析工具——Arthas火焰图
开发语言·python
Cobyte12 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc