• Flask 框架Ajax数据发送与接收


    ajax前端发送普通数据:

    <body>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function SendAjax(){
                $.ajax({
                    url:"/dataFromAjax",
                    contentType: "POST",
                    data:{"head":"hello lyshark"},
                    success:function(data){
                        if(data=="1"){
                            alert("请求已经提交.");
                        }
                    },
                    error:function(){
                         alert("执行失败了...")
                    }
                });
            }
        </script>
        <form action="/dataFromAjax" method="post">
            <input type="button" value="发送数据" onclick="SendAjax()">
        </form>
    </body>
    
    from flask import Flask,render_template,request
    app = Flask(__name__)
    
    @app.route("/")
    def index():
        return render_template("index.html")
    
    @app.route("/dataFromAjax",methods=['GET'])
    def recv():
        data = request.args.get("head")
        if(data==""):
            return "0"
        else:
            print("收到客户{} ".format(data))
            return "1"
    
    if __name__ == '__main__':
        app.run()
    

    ajax前端发送JSON数据:

    <body>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function SendAjax(){
                var username = $('input[name="username"]').val();
                var password = $('input[name="password"]').val();
                $.ajax({
                    url:"./dataFromAjax",
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    data: JSON.stringify({"username":username,"password":password}),
                    success:function(result){
                        alert("执行成功...");
                    },
                    error:function(){
                         alert("执行失败了...");
                    }
                });
            }
        </script>
        <form action="/dataFromAjax" method="post">
            用户账号: <input type="text" placeholder="用户账号" name="username" /><br><br>
            用户密码: <input type="text" placeholder="用户密码" name="password" /><br><br>
            <input type="button" value="发送数据" onclick="SendAjax()">
        </form>
    </body>
    
    from flask import Flask,render_template,request
    from flask import jsonify
    import json
    
    app = Flask(__name__)
    
    @app.route("/")
    def index():
        return render_template("index.html")
    
    @app.route("/dataFromAjax",methods=['POST'])
    def recv():
        data = request.get_data()
        json_data = json.loads(data)
        print(json_data)
        username = json_data.get("username")
        print(username)
        return  render_template("index.html")
    
    if __name__ == '__main__':
        app.run()
    

    ajax前端发送数据并携带token

    <body>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function SendAjax(){
                var token = $('input[name="token"]').val();
                $.ajax({
                    url:"./dataFromAjax",
                    type: "POST",
                    contentType: "application/json;charset=utf-8",
                    headers:{"Authorization":token},   <!--此处携带token-->
                    success:function(result){
                        alert("执行成功...");
                    },
                    error:function(){
                         alert("执行失败了...");
                    }
                });
            }
        </script>
        <form action="/dataFromAjax" method="post">
            设置token: <input type="text" placeholder="用户账号" name="token" /><br>
            <input type="button" value="发送数据" onclick="SendAjax()">
        </form>
    </body>
    
    from flask import Flask,render_template,request
    import json
    
    app = Flask(__name__)
    
    @app.route("/")
    def index():
        return render_template("index.html")
    @app.route("/dataFromAjax",methods=['POST'])
    def recv():
        token = request.headers.get("Authorization")
        print(token)
        return  render_template("index.html")
    
    if __name__ == '__main__':
        app.run()
    

    ajax接收服务器返回数据

    <body>
        <input type="button" class="MyButton" value="接收数据" onclick="GetAjax()">
        <script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            function GetAjax(){
                $.ajax({
                    url:"/dataFromAjax",
                    contentType: "GET",
                    success:function(data){
                        alert("姓名: " + data.name + "年龄: " + data.age);
                    },
                    error:function(){
                        alert("执行失败了...")
                    }
                });
            }
        </script>
    </body>
    
    from flask import Flask,render_template,request
    from flask import jsonify
    
    app = Flask(__name__)
    
    @app.route("/")
    def index():
        return render_template("index.html")
    
    @app.route("/dataFromAjax",methods=["GET","POST"])
    def set():
        info = dict()
        info['name'] = "lyshark"
        info['age'] = 22
        return jsonify(info)
    
    if __name__ == '__main__':
        app.run()
    
  • 相关阅读:
    27. Remove Element
    列表变成字典
    1. Two Sum
    CVPR2019:What and How Well You Performed? A Multitask Learning Approach to Action Quality Assessment
    959. Regions Cut By Slashes
    118. Pascal's Triangle
    loj3117 IOI2017 接线 wiring 题解
    题解 NOI2019 序列
    题解 省选联考2020 组合数问题
    题解 Educational Codeforces Round 90 (Rated for Div. 2) (CF1373)
  • 原文地址:https://www.cnblogs.com/LyShark/p/15670635.html
Copyright © 2020-2023  润新知