javascript - location.hash+iframe跨域获取不到值,什么原因?
ringa_lee
ringa_lee 2017-04-11 09:56:05
0
1
338

假设域名ajax.com下的文件test1.html要和ajax2.com域名下的cs.html传递信息。
1) test1.html首先创建自动创建一个隐藏的iframe,iframe的src指向ajax2.com域名下的cs.html页面
2) cs.html响应请求后再将通过修改test1.html的hash值来传递数据
3) 同时在test1.html上加一个定时器,隔一段时间来判断location.hash的值有没有变化,一旦有变化则获取获取hash值
注:由于两个页面不在同一个域下IE、Chrome不允许修改parent.location.hash的值,所以要借助于a.com域名下的一个代理iframe

现在打印不出结果,两个站点使用wampserver创建的,难道是因为本地相应不了?
我的代码如下:

//test1.html0----------ajax.com
<body>
<a href="#somedata">btn</a>
    <p id="somedata"></p>
<script>  
    var ifr = document.createElement('iframe');  
    ifr.style.display = 'none';  
    ifr.src = 'http://www.ajax2.com/cs.html#paramdo';  
    document.body.appendChild(ifr);  
 
function checkHash() {  
    try {  
        var data = location.hash ? location.hash.substring(1) : '';  
        if (console.log) {  
            console.log('Now the data is '+data);  
        }  
    } catch(e) {};  
}  
setInterval(checkHash, 2000);  
</script>
</body>
//cs.html 要跨域的文件------------ajax2.com
<body>
<a href="#paramdo">btn</a>
<p id="paramdo"></p>
    <script type="text/javascript">
switch(location.hash){  
    case '#paramdo':  
        callBack();  
        break;  
    case '#paramset':  
        //do something……  
        break;  
} 
function callBack(){  
    try {  
        parent.location.hash = 'somedata';  
    } catch (e) {  
        var ifrproxy = document.createElement('iframe');  
        ifrproxy.style.display = 'none';  
        ifrproxy.src = 'http://www.ajax.com/test2.html#somedata'; 
        document.body.appendChild(ifrproxy);  
    }  
}  
    </script>
</body>
//test2.html --------ajax.com
<body>
<a href="#somedata">btn</a>
    <p id="somedata">测试内容2</p>
    <script type="text/javascript">
        parent.parent.location.hash = self.location.hash.substring(1);
    </script>
</body>

打印结果

ringa_lee
ringa_lee

ringa_lee

全部回复(1)
黄舟

iframe跨域可以考虑 postMessage与onMessage进行组合
iframe不跨域 子页面直接使用window.parent.method()来执行父元素的方法

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!