Skip to content

Latest commit

 

History

History
54 lines (40 loc) · 1.85 KB

解决跨域.md

File metadata and controls

54 lines (40 loc) · 1.85 KB
  1. 同源
    • 同源策略:一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现
    • 同源:同协议、端口、域名
  2. 跨域(跨源)
    • 不同协议、端口、域名
  3. 协议:http,https,file
  4. 端口:专门提供某项服务的"窗口"
  5. 域名:IP的别名(方便记忆)如:www.baidu.com www.miaov.com
  6. 如何解决跨域
    • 通过 新版本的XMLHttpRequest + 服务器开权限 'Access-Control-Allow-Origin:*'
    • 服务器代理:服务器文件能访问别的域下的资源,如果服务器文件与自己的页面,是同源,我就能访问别的域下的资源了。
    • iframe
    • jsonp
  7. jsonp解决跨域的例子

    <body>
        <input type="text" id="txt">
        <ul id="ul">
    
        </ul>
    <script>
          function fn(obj){
            if(!obj.result) return;
            ul.innerHTML = '';
            obj.result.forEach((e,i)=>{
                if(!e[0]) return;
                var li = document.createElement('li');
    
                li.innerHTML = e[0];
    
                ul.append(li);
            });
    //        console.log(obj);
    
        }
        txt.onkeyup = function(){
            var os = document.createElement('script');
    //        os.src = `https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=${txt.value}&json=1&cb=fn`;
            os.src = `https://suggest.taobao.com/sug?code=utf-8&q=${txt.value}&_ksTS=1508925611668_322&callback=fn&k=1&area=c2c&bucketid=11`; // 淘宝地址
            document.getElementsByTagName('head')[0].appendChild(os);
            os.remove(); // 发送完请求就可以 删除script标签
        }
    </script>