首页 > 技术文章 > Jquery利用Iframe实现跨子域

sunbey 2016-10-11 11:59 原文

cross_sub.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cross sub domain</title>
    <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
</head>
<body>
    <script>
        document.domain = 'test.com'; //提升域
        var url = '/data/gameOut1.js';

        function doAjax(callback){
            $.ajax(url).done(function(data){
                callback(data);
            })
        }
    </script>
</body>
</html>

sub.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Cross sub domain</title>
    <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
</head>
<body>
    <iframe src="http://b.test.com/cross_sub.html" style="display: none;" id="bfrm" frameborder="0"></iframe>
    <script>
    window.onload = function(){
        function crossSub(){
            document.domain = 'test.com'; //提升域
            window.frames['bfrm'].contentWindow.doAjax(function(data){
                alert(data);
            })
        }

        crossSub();
    }
        
    </script>
</body>
</html>

 

http://a.test.com/sub.html 发起请求,通过提升域和引入iframe的方式,获取iframe子域中所请求接收的数据。

推荐阅读