七种跨域方法【7.location.hash篇】
来源:互联网 发布:淘宝pad版 编辑:程序博客网 时间:2024/06/05 10:55
问题描述:使用location.hash + iframe实现跨越现在本地页面a.html要访问异域b.html的数据怎么办?
环境配置:a.html 和 c.html我们放在php的wamp中运行他们的地址为:http://localhost/a.html和http://localhost/c.htmlb.html 的代码,我放在lamport.me/b.html中原理:1.a.html中有一个隐藏的frame,该frame指向异域lamport.me的b.html,且传递hash值给b.html2.b.html获取hash值,生成data值,然后动态创建iframe,该iframe将data值传给与a.html同域的c.html3.因为c.html与a.html同域,可以传值。
如果该文件不能访问,你可以在自己的wamp中配置一个虚拟主机进行访问虚拟主机的配置地址:http://blog.csdn.net/super_yang_android/article/details/53991982
本地http://localhost/a.html
<!doctype html><html><head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /> <title>localhost:a.html</title> <style type="text/css"> </style></head><body><script type="text/javascript"> alert('我是a页面'); function sendRequest(){ //动态创建个iframe var ifr = document.createElement('iframe'); ifr.style.display = 'none'; //跨域发送请求给b.html,参数是#sayHello ifr.src = 'http://lamport.me/b.html#sayHello'; document.body.appendChild(ifr); } function checkHash(){ var data = location.hash?location.hash.substring(1):''; if(data){ //这里处理返回值 alert(data); location.hash = ''; } } setInterval(checkHash,1000); window.onload = sendRequest;</script></body></html>
异域http://www.lamport.me/b.html
<!doctype html><html><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /><title>另某个域的:b.html</title><style type="text/css"></style></head><body><script type="text/javascript">function checkHash(){ var data = ''; //模拟一个简单的参数处理操作 switch(location.hash){ case '#sayHello': data = 'HelloWorld'; break; case '#sayHi': data = 'HiWorld'; break; default : break; } data && callBack('#'+data);}function callBack(hash){ var proxy = document.createElement('iframe'); proxy.style.display = 'none'; proxy.src = 'http://localhost/c.html'+hash; document.body.appendChild(proxy);}window.onload = checkHash;</script></body></html>
本地http://localhost/c.html
<!doctype html><html><head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /> <title>localhost:c.html</title></head><body><script type="text/javascript"> //因为c.html和a.html属于同一个域,所以可以通过改变其location.hash的值,可以通过parent.parent获取a.html的window对象 parent.parent.location.hash = self.location.hash.substring(1);</script></body></html>
0 0
- 七种跨域方法【7.location.hash篇】
- window.location.hash常用方法
- location.hash
- location hash(#)
- location.hash
- location.hash 与location.href
- window.location.hash解析
- javascript location.hash
- window.location.hash解析
- location.hash详解
- location.hash详解
- location.hash详解
- 25. Location hash 属性
- location.hash详解
- location.hash详解
- window.location.hash详解
- 【转载】location.hash详解
- window.location.hash详解
- windows从零使用gulp——修改静态文件名
- 析构函数小结
- 使用torch遇到的一些问题
- Oracle逐行相加
- 利用C++模板,代替虚函数,实现类的静态多态性
- 七种跨域方法【7.location.hash篇】
- mysql 5.5.29绿色安装
- Java IO 1:IO和File
- 百度地图api-浏览器如何实时定位、画出轨迹?
- php入门到放弃-define函数篇
- c语言里面的部分函数
- 用友3.0, 企业互联网化趋势
- RT-test in container
- 清理Xcode