###同源政策 所谓的同源就是指:
- 协议相同;
- 域名相同;
- 端口相同;
举例来说:http://www.haha.com/test/index.html ,这个网址协议是http:// ,域名是haha.com,端口是80(默认端口可以省略),它的同源情况如下: - http://www.haha.com/test1/index2.html 同源 - http://haha.com/test1/index2.html 不同源,域名不同 - https://haha.com/test1/index2.html 不同源,协议不同 - http://v2.www.haha.com/test1/index2.html 不同源,域名不同 - http://www.haha.com:81/test1/index2.html 不同源,端口不同
同源政策的存在是为了保证用户的信息,防止恶意网站窃取数据。(提交表单不受同源的限制),但也正是因为同源政策的存在导致Ajax要进行跨域
###受同源政策限制的行为:
- cookie,localStorage,indexDB
- Dom无法获取
- Ajax请求不能发送
###规避政策:
- Jsonp(只能发送get请求);webSocket;CORS是跨源Ajax请求的根本处理方法,允许任何类型的请求
- cookie:可以设置相同的document.domain;或者在cookie中指定cookie所属域名为一级域名
- localStorage:可以通过window.postMessage读取其他窗口的localStorage