日期:2014-05-16  浏览次数:20608 次

中间iframe 解决 js 跨域
已知a.html,c.html,其中c页面是a页面的子页面,且a、c不同域,求a,c页面互相访问的方案?
方案如下:
思路:
在a.html中增加与c.html同域的d.html,通过d.html访问c.html
在c.html中增加与a.html同域的b.html,通过b.html访问a.html

代码如下:
a.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>a.html</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <script type="text/javascript">
        var aPageContent = "a页面内容";
</script>
    </head>
    <body style="background-color: blue;">
         a页面:<br />
        <iframe name="cIframe" id="cIframe" src="http://www.hck.com:8080/WebTest/c.html"></iframe>
        <br />
        <br />
        <iframe name="dIframe" id="dIframe" src="http://www.hck.com:8080/WebTest/d.html"></iframe>
    </body>
</html>


b.html内容:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>a.html</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <script type="text/javascript">
    function test()
    {
        alert(top.aPageContent);
    }
   </script>
  </head>
  <body>
     b页面:a、b同域
     <button onclick="javascript:test();">调用A页面的内容</button>
  </body>
</html>


c.html页面内容:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>a.html</title>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script type="text/javascript">
    var cccc = "c页面的内容";
    </script>
  </head>
  <body>
  c页面:
  <iframe  src="http://www.xu.com:8080/WebTest/b.html"></iframe>
  </body>
</html>


d.html页面内容:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>a.html</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <script type="text/javascript">
    function test()
    {
        alert(top.frames[0].cccc);
    }
   </script>
  </head>
  
  <body>
     d页面:c、d同域
     <button onclick="javascript:test();">调用c页面的内容</button>
  </body>
</html>


说明:说明:a、b页面不是在www.hck.com域中的页面
图:



http://blog.csdn.net/lovingprince/article/details/2954675
http://www.cnblogs.com/rainman/archive/2011/12/06/1959325.html
http://www.nowamagic.net/ajax/ajax_KonwHowToCrossDomain.php