js中ajax的同源策略

一、什么是同源?

1995年由Netscape提出,现在所有浏览器都支持这一政策。
两个不同的网站无法互相访问同源策略限制的内容。

二、如何确定两个网页同源?

三个相同:
协议相同: http://或https://
域名相同: www.baidu.com
端口号相同: 80端口(默认80端口)
只有有一个不同那将不是同源。

三、设置同源的目的

设置同源策略的⽬的:保护⽤户数据安全,⽅式信息被恶意⻚⾯获取到。
A⽹站是⼀家银⾏,⽤户登录以后,又去浏览其他⽹站。如果其他⽹站可以读取A⽹站的 Cookie,会发⽣什么?

四、同源策略限制的范围

1、Cookie、localStorage、IndexDB⽆法读取。
2、DOM⽆法取得。
3、AJAX请求不能发送。

function    addScriptTag(src) {
var script  =
document.createElement('script');
        script.setAttribute("type","text/
javascript");
        script.src  =   src;
        document.body.appendChild(script);
}
window.onload = function () {
        addScriptTag('http://example.com/
ip?callback=foo');
}
function    foo(data) {
        console.log('Your   public  IP  address 
is: ' + data.ip);
};

五、ajax规避同源策略

规避同源策略:使用jsonp或者服务器端实现跨域。
一般使用服务器端实现跨域,因为jsonp既需要设置服务器端又要设置浏览器端,成本相对较高。而服务器端则只需要设置服务器端。
1、通过jsonp实现跨域请求
1)html内容:

// 1、创建script标签
            var scriptTag = document.createElement('script');
            // 2、配置标签属性
            scriptTag.type = 'text/javascript';
            scriptTag.src = 'http://10.0.156.213/data.php?cb=fn1';

            // 3、把标签拼接进文档流
            document.head.appendChild(scriptTag);
            // 回调函数
            function fn1(obj) {
                console.log(obj);
            }

2)服务器端代码(一般使用PHP写后台代码)


js中ajax的同源策略_第1张图片
jsonp.png

2、通过服务器端处理跨域

var xhr=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
            xhr.open('GET','http://wthrcdn.etouch.cn/weather_mini?city=北京',true);
            xhr.send(null);
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4&&xhr.status==200){
                    console.log(xhr.responseText);
                }
            }

请求路径上的链接地址一般是公共端口。

你可能感兴趣的:(js中ajax的同源策略)