用document.domain解决Ajax无法跨域问题

in 程序开发

因为浏览器的安全策略,浏览器不允许不同域(比如:dancewithnet.com和lab.dancewithnet.com)、不同协议(比如:http://dancewithnet.com和https://dancewithnet.com)、不同端口(比如:http:dancewithnet.com和http://dancewithnet.com:8080)下的页面通过XMLHTTPRequest相互访问,这个问题同样影响着不同页面的Javascript的相互调用和控制,但是当主域、协议、端口相同时,通过设置页面的document.domain主域,Javascript可以在不同的子域名间访问控制,比如通过设置document.domain=’dancewithnet.com’,http://dancewithnet.com和http://lab.dancewithnet.com页面可互访,这个特性也提供了此情况下不同子域名下的XMLHTTPRequest相互访问的解决方案。

对于主域、协议、端口相同时的Ajax跨域问题,很早就有设置document.domain来解决的说法,但一直没有看到具体的成功应用,这几天尝试了一下,其原理就是,利用一个隐藏的iframe引入所跨另一子域的页面作为代理,通过Javascript来控制iframe引入的另一子域的XMLHTTPRequest来进行数据获取。

<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script>
<script type="text/javascript">
_uacct = "UA-300049-1";
urchinTracker();
</script>
<h1>用document.domain解决Ajax跨子域</h1>
<h3><a href="http://dancewithnet.com/2007/07/22/solve-cross-sub-domain-ajax-with-document-domain/">说明</a>|<a href="http://dancewithnet.com/2007/07/22/solve-cross-sub-domain-ajax-with-document-domain/#comments">评论</a></h3>
<p>利用Ajax在dancewithnet.com域下获取http://lab.dancewithnet.com/2007/07/solve-cross-domain-ajax-with-document-domain/eg.txt的内容</p>
<p>方法1:<br /><button type="button" id="btn1">直接获取</button></p>
<p id="content1">如果方法1获取成功,此处文字将被Ajax获取的文字替换掉</p>
<p>方法2:<br /><button type="button" id="btn2">利用iframe代理获取</button></p>
<p id="content2">如果方法2获取成功,此处文字将被Ajax获取的文字替换掉</p>
<iframe src="http://lab.dancewithnet.com/2007/07/solve-cross-domain-ajax-with-document-domain/proxy.html" id="proxy"></iframe>
<script type="text/javascript" src="http://dancewithnet.com/lab/yui/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://dancewithnet.com/lab/yui/connection.js"></script>
<script type="text/javascript">

//<![CDATA[
document.domain = 'dancewithnet.com';
var $D = YAHOO.util.Dom;
var $  = $D.get;
var $E = YAHOO.util.Event;
var $C = YAHOO.util.Connect;

$E.on('btn1','click',getContent1);
var getContent1 = function(){
var sUrl = 'http://lab.dancewithnet.com/2007/07/solve-cross-domain-ajax-with-document-domain/eg.txt';
var request = $C.asyncRequest('GET',sUrl,{
success:function(o){
$('content1').innerHTML = o.responseText;
},
failure:function(){}
});
}
var getContent2 = function(){
var sUrl = 'http://lab.dancewithnet.com/2007/07/solve-cross-domain-ajax-with-document-domain/eg.txt';
var proxy = $('proxy').contentWindow;
var proxy$C = proxy.YAHOO.util.Connect;
var request = proxy$C.asyncRequest('GET',sUrl,{
success:function(o){
$('content2').innerHTML = o.responseText;
},
failure:function(){}
});
}
$E.on('btn2','click',getContent2);
//]]>

</script>

url:http://dancewithnet.com/2007/07/22/solve-cross-sub-domain-ajax-with-document-domain/

0 Comments