首页 > 语言 > JavaScript > 正文

Javascript 跨域访问解决方案

2024-05-06 14:16:06
字体:
来源:转载
供稿:网友
这里分两类情况:
一、基于同一父域的子域之间页面的访问;参见如下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脚本:
代码如下:
<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>

第二步:
完成域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
}
}
}

方案2:通过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];

方案3:隐藏iframe、共享domain:
即域A页面http://jipiao.taobao.com/yyyy.htm 的页面上写一个隐藏的iframe:
代码如下:
<html>
<head>
<head>
<body>
<script type="text/javascript" ><!--
Document.domain="taobao.com";
Var remoteHtml=document.getElementById("remoteHtml");

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选