【JavaScript38】jquery发送Ajax请求

发布时间 2023-08-12 22:03:31作者: Tony_xiao

发送get请求

from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/")
def func0():
    news = "这是一个完整的html页面"
    return render_template("index.html",
                           xwl_de_news=news,)


@app.route("/new_ajax",methods=["GET", "POST"])
def funccccc():
    uname = request.args.get('uname')
    age = request.args.get('age')

    print(uname, age)
    return '服务器返回的数据'
  • 前端
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/jquery_3.6.0_jquery.min.js"></script>
</head>
<body>
    {{ xwl_de_news }}
    <hr/>
    <button id="bbb">我是按钮</button>
    <script>
        $("#bbb").click(function(){
            // 发的get请求
            $.ajax({    // jquery封装好的ajax请求.
                // 发ajax的一些配置信息
                url: "/new_ajax?uname=xwl&age=18",
                method: "get",
                // 请求成功后. 你要做什么
                success: function(data){ // data表示返回的内容
                    console.log(data);
                }
            });
        });
    </script>
</body>
</html>

POST请求

  • 服务器端
from flask import Flask, render_template, request, make_response


app = Flask(__name__)
# http://127.0.0.1:5000/
@app.route("/")
def func0():
    news = "这是一个完整的html页面"
    return render_template("index.html",
                           xwl_de_news=news,)

# jsonp的逻辑
@app.route("/new_ajax",methods=["GET", "POST"])
def funccccc():
    uname = request.form.get('uname')
    age = request.form.get('age')
    print(uname, age)
    return '服务器返回的数据'

  • 前端
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/jquery_3.6.0_jquery.min.js"></script>
</head>
<body>
    {{ xwl_de_news }}
    <hr/>
    <button id="bbb">我是按钮</button>
    <script>
        $("#bbb").click(function(){
            $.ajax({
                url: "/new_ajax",
                method: 'post',
                data: { // 发请求的参数
                    uname: "xwl",
                    age: 188
                },
                success:function(data){ // 返回的参数
                    console.log(data);
                }
            })
        });
        // 如果网站的返回的数据被加密了. 解密去哪儿找?
        // 去success找.
    </script>
</body>
</html>