JSONP跨域请求

一、什么是JSONP

        JSONP(JSONP - JSON with Padding是JSON的一种“使用模式”),利用script标签的src属性(浏览器允许script标签跨域)。浏览器的同源策略限制从一个源加载的文档或脚本与来自另一个源的资源进行交互。如果要在js里发起跨域请求,则要进行一些特殊处理了,这里将介绍JSONP的使用。

二、JSONP使用:

模拟跨域环境:两个端口不一样,构成跨域请求的条件。

这是请求端,端口8086:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSONP</title>
</head>
<body>
    <p><input type="submit" value="JSONP原理点我" onclick="AjaxSubmitJsonp1()"></p>

    <p><input type="submit" value="JSONP点我" onclick="AjaxSubmitJsonp2()"></p>
    <script src="/static/jq/jquery-3.3.1.min.js"></script>
    <script>
        function AjaxSubmitJsonp1() {
            var tag = document.createElement('script');
            tag.src = 'http://127.0.0.1:9000/jsonp.html';
            document.head.appendChild(tag);
            document.head.removeChild(tag);
        }
        function func(arg) {        //这里的函数名是后台发送过来包裹数据的函数名,不然不能执行
            console.log(arg)
        }

        function AjaxSubmitJsonp2() {
            $.ajax({
                {#url:'http://127.0.0.1:9000/jsonp.html?callback=list',#}
                url:'http://127.0.0.1:9000/jsonp.html',
                type:'GET',                     //只能是GET,如果是POST也会被转换为GET
                dataType:'JSONP',               //自动帮我们创建script块拿到数据后并删除
                jsonp:'callback',               //等于上面'http://127.0.0.1:9000/jsonp.html?callback=list'
                jsonpCallback:'list'
            });
        }
        function list(arg) {
            console.log(arg);
        }
    </script>
</body>
</html>
View Code

服务端,端口9000:

from django.shortcuts import render,HttpResponse

# Create your views here.
def jsonp(request):
    # return HttpResponse("func('this is jsonp')")      # 原理

    name = request.GET.get('callback')        #获取包裹数据的函数名
    print(name)
    return HttpResponse("%s('this is jsonp')" % name)
View Code

效果图:

JSONP跨域请求