Javascript 跨域访问解决方案


由于安全方面的考虑,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脚本

  <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);
</script>

第二步:

  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 }
}
}
<!--[if !supportLists]-->② <!--[endif]-->Script标签: 域A页面http://Jipiao.taobao.com/test.htm 的head中写一个空的Script标签
<html>
<head>
 <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]);
</script>
</body>
</html>

  注意:这种方案要求域B返回的数据必须是合法的JSON格式或者如JS文件的格式。

  域B返回的数据格式如下:

Var remote={test:’hello’};
Var f=[‘2,1];

  对于基于同一父域的子域之间页面的访问这一类情况,还有第三种方式
③ 隐藏iframe: 即域A jipiao.taobao.com/yyyy.htm 的页面上写一个隐藏的iframe,

<html>
<head>
<head>
<body>
<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的数据了
</script>
<iframe id=”remoteHtml” src=”” style=”diapay:none”/>
</body>
</html>

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

本文作者:
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3