Javascript跨域访问解决方案

由于安全方面的考虑,Javascript被限制了跨域访问的能力,但是有时候我们希望能够做一些合理的跨域访问的事情,那么怎么办呢?
这里分两类情况:
一、基于同一父域的子域之间页面的访问;参见如下3个domain域:taobao.com、jipiao.taobao.com、promotion.taobao.com;它们有相同的父域taobao.com。
二、基于不同父域页面之间的访问;参见如下3个domain域:taobao.com、baidu.com、sina.com.cn;它们具有不同的父域。

解决它们之间跨域的方案有:
方案1:服务器Proxy
域A的页面JS需要访问域B下的链接获取数据,该方案在域A的服务器端建立一个Proxy程序(可能是ASP、servlet等任何服务端程序),域A的页面JS直接调用本域下的Proxy程序,proxy程序负责将请求发送给域B下的链接并获取到数据,最后再通过Proxy将数据返回给页面JS使用。
经过的访问流程就是: 域A下JS --> 域A 下Proxy -- > 域B下的链接
例子:
第一步:
域A: http://Jipiao.taobao.com/test.htm
页面上javascript脚本:

  1. <mce:script type="text/javascript"><!--   
  2. Var sUrl="http://Jipiao.taobao.com/proxy.do"; //本域下代理地址   
  3. var callback =   
  4. {   
  5.     success: function(res) {   alert(res.responseText);   },   
  6.     failure: function(res) {   alert('failure');},   
  7.     argument:{}   
  8. }   
  9. YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);     
  10. // --></mce:script>  

<textarea class="javascript:firstline[1]" cols="50" rows="15" name="code"><mce:script type="text/javascript"><!-- Var sUrl="http://Jipiao.taobao.com/proxy.do"; //本域下代理地址 var callback = { success: function(res) { alert(res.responseText); }, failure: function(res) { alert('failure');}, argument:{} } YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null); // --></mce:script> </textarea> 
第二步:
完成域A服务端的Proxy程序(这里假定是一个servlet),伪码如下:

  1. Public class Proxy extends …….{   
  2. ..doGet(……..){   
  3. HttpClient   client=……;   
  4. GetMethod get=new   GetMethod("www.baidu.com/xxxxx.do");//访问域B的链接   
  5. int statusCode = client.executeMethod(get);   
  6. if (statusCode != HttpStatus.SC_OK) {   
  7.      byte[] responseBody = get.getResponseBody();   
  8.       String res=new String(responseBody);   
  9.       Httpresponse.getWriter().write(res);//将数据返回给域A     
  10. }   
  11. }   
  12.   
  13. }  

<textarea class="java:firstline[1]" cols="50" rows="15" name="code">Public class Proxy extends …….{ ..doGet(……..){ HttpClient client=……; GetMethod get=new GetMethod("www.baidu.com/xxxxx.do");//访问域B的链接 int statusCode = client.executeMethod(get); if (statusCode != HttpStatus.SC_OK) { byte[] responseBody = get.getResponseBody(); String res=new String(responseBody); Httpresponse.getWriter().write(res);//将数据返回给域A } } } </textarea>

 

方案2:通过Script标签
在域A页面http://Jipiao.taobao.com/test.htm 的head中写一个空的Script标签:

  1. <html>  
  2. <head>  
  3. <mce:script id="remoteScript" type="text/javascript" src=""/><!--   
  4. <head>  
  5. <body>  
  6. <script type="text/javascript" >  
  7. Var remoteScript=document.getElementById("remoteScript");   
  8. remoteScript.src="www.baidu.com/xxxxx.do";//域B的链接   
  9. alert(remote.test);//使用域B返回的JSON数据   
  10. alert(f[0]);   
  11. // --></mce:script>  
  12. </body>  
  13. </html>  

<textarea class="xhtml:firstline[1]" cols="50" rows="15" name="code"><html> <head> <mce:script id="remoteScript" type="text/javascript" src=""/><!-- <head> <body> <script type="text/javascript" > Var remoteScript=document.getElementById("remoteScript"); remoteScript.src="www.baidu.com/xxxxx.do";//域B的链接 alert(remote.test);//使用域B返回的JSON数据 alert(f[0]); // --></mce:script> </body> </html> </textarea>

 

注意:这种方案要求域B返回的数据必须是合法的JSON格式或者如JS文件的格式;比如域B返回的数据格式如下:
Var remote={test:’hello’};
Var f=[2,1];

方案3:隐藏iframe、共享domain:
即域A页面http://jipiao.taobao.com/yyyy.htm 的页面上写一个隐藏的iframe:

  1. <html>  
  2. <head>  
  3. <head>  
  4. <body>  
  5. <mce:script type="text/javascript" ><!--   
  6. Document.domain="taobao.com";   
  7. Var remoteHtml=document.getElementById("remoteHtml");   
  8. remoteHtml.src="promotion.taobao.com/xxxx.htm";//这里访问域B的链接   
  9. var document=remoteHtml.ContentDocument; //这里就可以使用document来操作域B中页面xxx.htm的数据了   
  10. // --></mce:script>  
  11. <iframe id="remoteHtml" src="" style="diapay:none" mce_style="diapay:none"/>  
  12. </body>  
  13. </html>  

<textarea class="xhtml:firstline[1]" cols="50" rows="15" name="code"><html> <head> <head> <body> <mce:script type="text/javascript" ><!-- Document.domain="taobao.com"; Var remoteHtml=document.getElementById("remoteHtml"); remoteHtml.src="promotion.taobao.com/xxxx.htm";//这里访问域B的链接 var document=remoteHtml.ContentDocument; //这里就可以使用document来操作域B中页面xxx.htm的数据了 // --></mce:script> <iframe id="remoteHtml" src="" mce_/> </body> </html> </textarea>

 

注意:这里http://promotion.taobao.com/xxxx.htm 页面也需要设置document.domain="taobao.com", 这种方法才能奏效。
之所以这种iframe的方法不适合不同父域之间的跨域,是因为设置document.domain只能设置为自己的父域,而不是能设置为其他域,例如:jiapiao.taobao.com只能设置document.domain="taobao.com",而不能是document.domain="baidu.com";

这里列举的三种方案各有优缺点
Proxy方案优点是可以适用用于几乎所有的跨域访问,而且只需要要一个域中进行开发,另一个域可以提供任何类型格式的数据。缺点是这种方案经过了中间Proxy,所以延迟可能稍微大一点,并且会加重本域服务器的负荷,开发工作量也稍微大一点。
Script标签的方案可以说是非常简单的,不用几行代码就搞定了事,不过它对返回的数据格式要求有点严格,只能是Json格式数据,如果是其他格式的数据,那么这种方法就无能为力了。
隐藏iframe方式也很简单,它可以处理任何返回的数据格式,但它只适用在具有同一个父域下的跨域请求上,并且要求其他域得配合开发,即需要设置document.domain。

原帖详见:http://blog.csdn.net/lovingprince/archive/2008/09/20/2954675.aspx

 

 


 

 

 

 


 

 

对于JS跨域访问的意思,我想再补充几点:

  1. 跨域访问,简单来说就是 A 网站的 javascript 代码试图访问 B 网站,包括提交内容和获取内容;比如想从A网站的页面中执行另外一个B网站内某页面中的JS对象、或者想在A网站的页面中用JS去解析B网站内某页面的dom元素等;出现这种跨域访问问题的应用场景一般是iframe中嵌入不同域的页面、或者向不同域发送Ajax请求等;
  2. 由于安全原因,跨域访问是被各大浏览器所默认禁止的;但是浏览器并不禁止在页面中引用其他域的JS文件,并可以自由执行引入的JS文件中的function;这点个人觉得至关重要!
  3. 是否跨域的判断规则为对三者进行比较:域名、协议、端口;三者中若有一个不相同,则会出现跨域问题;我们经常说的跨域问题一般指域名不同,因为这种场景出现的几率最高而且有一些办法可以解决;比如前面提到的taobao.com域下的二级域名跨域问题;
  4. 对于主域都不一样、或者协议不同(比如https与http)的跨域问题(比如*.taobao.com域想访问*.baidu.com域内的内容),想从Web端来解决是完全不可能的,只能通过服务端Proxy的方案来解决;
  5. 常见的不同域间的页面制约dom元素包括: 
    window.location 可以设置,但不能读取。其它的 location 属性和方法被禁止访问; 
    document.href 可以设置,但不能读取。其它的 document 属性和方法被禁止访问; 
    <iframe> 的 src 可以设置,但不能读取;
posted @ 2011-11-20 03:33  潺莪  阅读(253)  评论(0编辑  收藏  举报