zoukankan      html  css  js  c++  java
  • 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

    效果图:

  • 相关阅读:
    USACO--2.1The Castle
    浅谈python字符串存储形式
    面向对象——一起来复习托付与事件!
    数据结构——算法之(032)(求两个串中的第一个最长子串)
    读《浪潮之巅》有感
    关于android 怎样安装 assets文件下的apk
    每日一小练——求质数
    怎样使破解网页的禁止复制黏贴
    Angularjs Nodejs Grunt 一个样例
    《TCP/IP具体解释卷2:实现》笔记--域和协议
  • 原文地址:https://www.cnblogs.com/ray-h/p/10202570.html
Copyright © 2011-2022 走看看