js跨域传输数据实例(单向)

http://localhost/getDomainData.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" > 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head> 
    <title>跨域获取数据</title> 
    <script type="text/javascript"> 
    function domainData(url, fn) 
    { 
        var isFirst = true; 
        var iframe = document.createElement('iframe'); 
        iframe.style.display = 'none'; 
        var loadfn = function(){ 
            if(isFirst){ 
                iframe.contentWindow.location = 'http://localhost/null.html'; 
                isFirst = false; 
            } else { 
                fn(iframe.contentWindow.name); 
                iframe.contentWindow.document.write(''); 
                iframe.contentWindow.close(); 
                document.body.removeChild(iframe); 
                iframe.src = ''; 
                iframe = null; 
            } 
        }; 
        iframe.src = url; 
        if(iframe.attachEvent){ 
            iframe.attachEvent('onload', loadfn); 
        } else { 
            iframe.onload = loadfn; 
        } 
          
        document.body.appendChild(iframe); 
    } 
    </script> 
</head> 
 


<body> 
  

    <script type="text/javascript"> 
    domainData('http://127.0.0.3/data.html', function(data){ 
        alert(data); 
    }); 
    </script> 
</body> 
</html>

http://localhost 添加一个空HTML页。名称为:http://localhost/null.html,是必须的。内容可为空。

http://127.0.0.3/data.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>b域名</title>
<script> 
  window.name = '需要跨域传递的数据'; 
</script>
</head>

<body>
</body>
</html>

浏览 http://localhost/getDomainData.html 即 获得127.0.0.3域名下data.html传输的值

调用domainData函数必须在body后面,或页面加载完后。

调用时会执行 http://b.com/data.html 页面的脚本。

posted @ 2013-01-12 11:31  tinyphp  Views(608)  Comments(0Edit  收藏  举报