关于document.domain的一点tips

 
首先,关于 same origin policy,简单描述如下:
http://store.company.com/dir2/other.html => Success  

http://store.company.com/dir/inner/another.html =>Success  

https://store.company.com/secure.html =>Failure => Different protocol

http://store.company.com:81/dir/etc.htm => Failure => Different port

http://news.company.com/dir/other.html => Failure => Different host

众所周之,在ajax中,post受到same origin policy的限制,是不能跨域的。这个限制是在浏览器内部完成的。

但是对于同一个域下的不同子域,在一些条件下还是可以跨域post的。

测试环境,如下三个域:
############# test
127.0.0.1   tt1.test.com
127.0.0.1   tt2.test.com
127.0.0.1   test.com

然后设定一个html页面: 4.html, 放到 http://tt1.test.com 下,我们将利用它去跨域post

关键代码如下:
4.html

<script type="text/javascript">
 
 alert(document.domain);
 
 alert("begin cross domain ajax action!");
 
 document.domain = "test.com";
 
 alert(document.domain);

......
(xmlhttprequest实现)
......

var xmlhttp = new XmlHttp();
if (xmlhttp.init()) {
 var url = "http://test.com/4.txt";

 alert("ajax get");
 xmlhttp.get(url, null, function(response, responseHeaders) {
  if (responseHeaders != null) {
   alert(responseHeaders);
  }

  if (response != null) {
   alert(response);
  }
 });


        alert("ajax post");
 xmlhttp.post(url, "", null, function(response, responseHeaders) {
  if (responseHeaders != null) {
   alert(responseHeaders);
  }

  if (response != null) {
   alert(response);
  }
 });
 

 
}

那么通过改变 document.domain 的值,可以得到什么结果呢?

在IE 6 , 安全级别为 时,有如下测试结果:
document.domain = "test.com";
    ajax post("http://test.com/4.txt"); 失败
    ajax post("http://tt2.test.com/4.txt"); 失败 
document.domain = "tt2.test.com";   失败,不允许这样设置


在IE 6 , 安全级别为 时, 有如下测试结果:
document.domain = "test.com";
    ajax post("http://test.com/4.txt"); 成功
    ajax post("http://tt2.test.com/4.txt"); 成功 
document.domain = "tt2.test.com";  失败,不允许这样设置
 
在Firefox 中,无论怎么设置,都无法跨子域post



所以,我们得到结论:

在IE 6中, 跨子域post实际上是和IE的安全级别(Internet Explorer Security Zone)有关系的。

当安全级别为低时,才可以通过设置document.domain来跨子域post数据。

而Firefox则严格禁止了跨域post。




更新(2008-08-22):我犯了一个经验主义错误,纠正一下。

当IE安全级别为低时,不需要修改document.domain即可跨子域post。 
所以本文在这里用document.domain来测试不太合适,因为跟他没关系了。
不过IE允许JS修改document.domain确实会带来一些安全隐患。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值