解決它們之間跨域的方案有:
方案1:服務(wù)器Proxy
域A的頁(yè)面JS需要訪問(wèn)域B下的鏈接獲取數(shù)據(jù),該方案在域A的服務(wù)器端建立一個(gè)Proxy程序(可能是ASP、servlet等任何服務(wù)端程序),域A的頁(yè)面JS直接調(diào)用本域下的Proxy程序,proxy程序負(fù)責(zé)將請(qǐng)求發(fā)送給域B下的鏈接并獲取到數(shù)據(jù),最后再通過(guò)Proxy將數(shù)據(jù)返回給頁(yè)面JS使用。
經(jīng)過(guò)的訪問(wèn)流程就是: 域A下JS --> 域A 下Proxy -- > 域B下的鏈接
例子:
第一步:
域A: http://Jipiao.taobao.com/test.htm
頁(yè)面上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服務(wù)端的Proxy程序(這里假定是一個(gè)servlet),偽碼如下:
代碼如下:
Public class Proxy extends …….{
..doGet(……..){
HttpClient client=……;
GetMethod get=new GetMethod("www.baidu.com/xxxxx.do");//訪問(wèn)域B的鏈接
int statusCode = client.executeMethod(get);
if (statusCode != HttpStatus.SC_OK) {
byte[] responseBody = get.getResponseBody();
String res=new String(responseBody);
Httpresponse.getWriter().write(res);//將數(shù)據(jù)返回給域A
}
}
}
方案2:通過(guò)Script標(biāo)簽:
在域A頁(yè)面http://Jipiao.taobao.com/test.htm 的head中寫一個(gè)空的Script標(biāo)簽:
代碼如下:
<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數(shù)據(jù)
alert(f[0]);
// --></script>
</body>
</html>
注意:這種方案要求域B返回的數(shù)據(jù)必須是合法的JSON格式或者如JS文件的格式;比如域B返回的數(shù)據(jù)格式如下:
Var remote={test:'hello'};
Var f=[2,1];
方案3:隱藏iframe、共享domain:
即域A頁(yè)面http://jipiao.taobao.com/yyyy.htm 的頁(yè)面上寫一個(gè)隱藏的iframe:
代碼如下:
<html>
<head>
<head>
<body>
<script type="text/javascript" ><!--
Document.domain="taobao.com";
Var remoteHtml=document.getElementById("remoteHtml");
新聞熱點(diǎn)
疑難解答
圖片精選