PHP下ajax跨域的解决方案之window.name实例分析

来自:互联网
时间:2020-03-07
阅读:

本文实例讲述了PHP下ajax跨域的解决方案之window.name。分享给大家供大家参考,具体如下:

原理核心:window对象的name属性是一个很特别的属性,当该window的location变化,然后重新加载,它的name属性可以依然保持不变。

依此原理,我们可以在页面A中用iframe加载其他域的页面B,而页面B中用JavaScript把需要传递的数据赋值给 window.name,页面A的iframe加载完成之后,页面A修改iframe的地址,将其变成同域的一个地址,然后就可以读出window.name的值了。

例:有两个网站www.a.com和www.b.com,我们要在www.a.com/a.html下获取www.b.com/data.html数据。

我们需要三个文件:

www.a.com 下的 a.html 获取数据并显示
www.b.com 下的data.html 提供数据
www.a.com 下的proxy.html 代理文件,与a.html同一域下,一般为空html文件。

www.b.com下的data.html如下:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Insert title here</title>
</head>
<body>
  <script type="text/javascript">
    //添加需要传递的数据,大小一般为2M,IE和firefox下可以大至32M左右
    window.name = '[{"name":"test1"},{"name":"test2"}]';
  </script>
</body>
</html>

www.a.com下的proxy.html如下:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Insert title here</title>
</head>
<body>
  <!-- 空的html文件 -->
</body>
</html>

www.a.com下的a.html如下:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Insert title here</title>
</head>
<body>
 
<!-- 用于引用www.b.com/data.html文件 -->
<iframe id="iframe" src=""></iframe>
 
<!-- 显示获取到的数据 -->
<div id="data"></div>
 
<script type="text/javascript" src="./jquery.js"></script>
<script type="text/javascript">
var ifr = document.getElementById("iframe");
ifr.src = "http://www.b.com/data.html";
if (ifr.attachEvent) {
  ifr.attachEvent("onload", loadfunc);
} else {
  ifr.onload = loadfunc;
}
 
var state = 0;
function loadfunc() {
  if(state == 0) {
    state = 1;
    ifr.contentWindow.location = "http://www.a.com/proxy.html";
  } else {
    var data = ifr.contentWindow.name;
    $.each($.parseJSON(data), function(i, v) {
      $("#data").append(v.name);
    });
     
    //销毁iframe,保证安全
    ifr.contentWindow.document.write("");
    ifr.contentWindow.close();
    document.body.removeChild(ifr);
  }
}
</script>
</body>
</html>

返回顶部
顶部