AJAX跨域请求和CORS跨域资源共享

同源策略限制:

同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果没有同源策略,攻击者可以通过JavaScript获取你的邮件以及其他敏感信息,比如说阅读私密邮件,发送虚假邮件,查看聊天记录等等。所谓同源是指,协议,域名,端口相同。三者只有有一个不相同,就认为不同源!

例如:域:http://store.company.com/dir/index.html

跨域请求:

1. 对于主域相同而子域不同的例子,可以通过设置document.domain的办法来解决。

ajax不允许跨子域请求,但是iframe可以!可以通过提升域的方法来实现。

例如www.a.com/a.html和a.com/b.html为例,只需在a.html中添加一个b.html的iframe,并且设置两个页面的document.domain都为’a.com’(只能为主域名),两个页面之间即可互相访问了。

如果b.html要访问a.html,可在子窗口(iframe)中通过window.parent来访问父窗口的window对象。

例如www.a.com/a.html中的script:

document.domain='a.com';//提升域
varifr = document.createElement('iframe');
ifr.src = 'http://a.com/b.html';
ifr.style.display = 'none';
document.body.appendChild(ifr);
ifr.onload = function(){
   
  //获取iframe的document对象
  //W3C的标准方法是iframe.contentDocument,
  //IE6、7可以使用document.frames[ID].document
  //为了更好兼容,可先获取iframe的window对象iframe.contentWindow
  vardoc = ifr.contentDocument || ifr.contentWindow.document;
  // 在这里操纵b.html
  alert(doc.getElementById("test").innerHTML);

而a.com/b.html:

<!DOCTYPE >
<html>
<head>
<title></title>
<scripttype="text/javascript">
  document.domain='a.com';//提升域
</script>
</head>
<body>
<h1id="test">Hello World</h1>
</body>
</html>
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值