日期:2014-05-16  浏览次数:20404 次

(转) JavaScript跨域总结与解决办法2
由于安全方面的考虑, Javascript 被限制了跨域访问的能力,但是有时候我们希望能够做一些合理的跨域访问的事情,那么怎么办呢?

这里分两类情况:

         一、基于同一父域的子域之间页面的访问
                 参见如下 3 个 domain 域:
1 、 taobao.com
          2 、 jipiao.taobao.com
          3 、 promotion.taobao.com
它们有相同的父域   taobao.com

         二、基于不同父域页面之间的访问
                 参见如下 3 个 domain 域:
1 、 taobao.com
             2 、 baidu.com
3 、 sina.com.cn
     它们具有不同的父域。

解决它们之间跨域的方案:
<!--[if !supportLists]-->① <!--[endif]-->服务器 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 脚本

[javascript] view plaincopyprint?
   <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>  


第二步:
Proxy 程序 ( 这里假定是一个 servlet) :

 
[java] view plaincopyprint?
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);// 
将数据返回给域 

 
 
    }  
 
}  
 
}  
 
<!--[if !supportLists]-->② <!--[endif]-->  Script 标签 : 域 A 页面 http://Jipiao.taobao.com/test.htm 的 head 中写一个空的 Script 标签
[xhtml] view plaincopyprint?
<html>  
 
  <head>  
 
  <mce:script id=”remoteScript” type=”text/javascript” src="””" mce_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]);  
/