【JavaScript40】jquery发送jsonp

发布时间 2023-08-12 22:13:43作者: Tony_xiao

jquery中也提供了jsonp请求

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

app = Flask(__name__)
@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():
    cb = request.args.get("zhoujielun")
    uname = request.args.get('uname')
    age = request.args.get('age')

    print(uname, age)
    resp = make_response(f"{cb}('哈哈');")  # 返回的是js代码
    return resp
  • 客户端
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 注意, 浏览器访问静态资源, 没有跨域问题. -->
    <script src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    我是一个完整的html

    <button id="bbb">我是按钮</button>
    <script>
        $("#bbb").click(function(){
            let url = "http://127.0.0.1:5000/new_ajax?uname=xwl&age=18";
            $.ajax({
                url: url,
                method: "get",
                dataType:"jsonp",
                jsonp: "zhoujielun", // callback
                success: function(data){
                    // jquery的ajax返回值. 直接找success
                    console.log("接受到的数据是", data);
                }
            });
        });

    </script>
</body>
</html>