`

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脚本:

     <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> 


第二步:
完成域A服务端的Proxy程序(这里假定是一个servlet),伪码如下:

      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    
     }  
    }  
 
   } 

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 } } }


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

     <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> 


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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics