js跨域問題

microsoft_kk發表於2013-07-03

jsonp方式:

  <script src="http://www.baidu.com/xxx.php?key=0&type=0&callback=hander" />

  返回js:function hander(1,2,3);

window.name方式:

  window.name 不會因為訪問的頁面不同而改變。

  本地檔案1:a.html

  本地檔案2:b.html (空白檔案)

  外域檔案:c.html

 

  a.html

  

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8" />
        <title>a.html</title>
    </head>
    <body>
    </body>
</html>
        <script type="text/javascript">
            (function(){
                var load=0;
                var ifr=document.createElement('iframe');
                ifr.style.display='none';
                ifr.src='http://192.168.1.154/DMS/c.html'; //c.html 不在同一域 載入後window.name已經有值
                ifr.onload=function(){
                    if(load===1){
                        alert(ifr.contentWindow.name);
                    }else{
                        load=1;
                        ifr.contentWindow.location.href='b.html'; //b.html
                    }
                }
                document.body.appendChild(ifr);
            })();
        </script>

 

c.html

<script>window.name='hello js!'</script>

 

相關文章