• 同源&跨域


    1 同源

    同源策略是浏览器的一种安全策略,所谓同源是指,域名,协议,端口完全相同。

    同源策略的限制 

          1 Cookie、LocalStorage 和 IndexDB 无法读取

          2  无法操作跨域的iframe里的dom元素

          3  AJAX 请求不能发送 

    2 跨域

    不同源则跨域 例如http://www.example.com/

    http://api.example.com/detail.html  不同源 域名不同  
    https//www.example.com/detail.html   不同源 协议不同  http://www.example.com:8080/detail.html    不同源    端口不同  http://api.example.com:8080/detail.html    不同源    域名、端口不同  https://api.example.com/detail.html    不同源    协议、域名不同  https://www.example.com:8080/detail.html    不同源    端口、协议不同  http://www.example.com/detail/index.html    同源    只是目录不同  

    3 跨域方案

    1、顶级域名相同的可以通过domain.name来解决,即同时设置 domain.name = 顶级域名(如example.com)

    <iframe id="iframe" src="http://api.study.com/domain.html" frameborder="0"></iframe>
    <script>
    // 这种情况适合 顶级域名相同的情况
    // 测试时需要配置一个二级域名
    document.domain = 'study.com';
    2、document.domain + iframe
    3、window.name + iframe

    4、location.hash + iframe

    <iframe id="iframe" src="http://api.study.com/hash.html#name|xjj" frameborder="0"></iframe>

    5、window.postMessage()

    参考资料 http://rickgray.me/2015/09/03/solutions-to-cross-domain-in-browser.html

    4、 jsonp(自认为重点)

    JSON with Padding

    1、原理剖析

    其本质是利用了标签具有可跨域的特性, 由服务端返回一个预先定义好的Javascript函数的调用,并且将服务器数据以该函数参数的形式传递过来, 此方法需要前后端配合完成。

    <!--
    当我们用script标签去加载的时候  会把内容解析成js去执行
    --><script>function fuc(data){
            console.log(data.name);
        }
    </script><scriptsrc="http://www.guangzhou.com/api.php?callback=fuc"></script>
    $(function(){//jQ中的有ajax的方法  可直接解决跨源的问题  只需要dataType:'jsonp'  返回数据data就是所需数据,用前打印看看是怎样的数据类型,还的结合后台给的端口数据
    $.ajax({
    type:'get',
    url:'http://api.study.com/01.php',
    dataType:'jsonp',
    //jsonpCallback:'test()',
    success:function(data){
    var data = JSON.parse(data);
    console.log(data.name);
    },
    error:function(){
    console.log(1);
    }
    });
    });



  • 相关阅读:
    hdu 4002 Find the maximum
    hdu 2837 坑题。
    hdu 3123
    zoj Treasure Hunt IV
    hdu 2053 Switch Game 水题一枚,鉴定完毕
    poj 1430 Binary Stirling Numbers
    hdu 3037 Saving Beans
    hdu 3944 dp?
    南阳oj 求N!的二进制表示最低位的1的位置(从右向左数)。
    fzu 2171 防守阵地 II
  • 原文地址:https://www.cnblogs.com/zhanggaojun/p/5745017.html
Copyright © 2020-2023  润新知