window.name实现跨域请求

如a.com网站想通过JS获取b.com网站的数据。

1 在a.com网站添加一个空HTML页。名称为:http://a.com/null.html

2 在a.com网站需要获取数据页面(如:http://a.com/getDomainData.html)内容如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>跨域获取数据</title>
    <script type="text/javascript">
    function domainData(url, fn)
    {
		var isFirst = true;
		var iframe = document.createElement('iframe');
		iframe.style.display = 'none';
		var loadfn = function(){
			if(isFirst){
				iframe.contentWindow.location = 'http://a.com/null.html';
				isFirst = false;
			} else {
				fn(iframe.contentWindow.name);
				iframe.contentWindow.document.write('');
				iframe.contentWindow.close();
				document.body.removeChild(iframe);
				iframe.src = '';
				iframe = null;
			}
		};
		iframe.src = url;
		if(iframe.attachEvent){
			iframe.attachEvent('onload', loadfn);
		} else {
			iframe.onload = loadfn;
		}
	    
		document.body.appendChild(iframe);
    }
    </script>
</head>
<body>

</body>
    <script type="text/javascript">
    domainData('http://b.com/data.html', function(data){
		alert(data);
    });
    </script>
</html>

3 在b.com中添加获取数据页面 如:http://b.com/data.html 内容需包含:

 

<script>
  window.name = '需要跨域传递的数据';
</script>

4 访问 http://a.com/getDomainData.html 就可返回 http://b.com/data.html 中的window.name中的数据了。

需要注意的地方

null.html 是必须的。内容可为空。

 iframe的onload事件绑定 必须这样写:

if(iframe.attachEvent){
	 iframe.attachEvent('onload', loadfn);
} else {
	 iframe.onload = loadfn;
}

调用domainData函数必须在body后面,或页面加载完后。

调用时会执行 http://b.com/data.html 页面的脚本。

原创话语:之前听说过window.name可以实现跨域,但是安全性值得商榷,不过既然是跨域,除了html5的postmessage之外貌似安全性都不高,

所以将其纳入跨域请求行列。

文章转载自 http://www.cnblogs.com/zjfree/ 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值