有a.ceshi.com通过iframe加载b.ceshi.com下的内容,通过对两个子域下的页面同时设置document.domian设置为相同的主域名可实现跨域读取数据:

 

a.ceshi.com页面

<!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" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>ceshi1</title>
</head>
<body>
    我是1
<div id="box1"></div>
<script type="text/javascript">
//设置主域
document.domain = 'ceshi.com';
var iframe = document.createElement("iframe"); 
iframe.style.display = 'none';
//拉取b.ceshi.com内容
iframe.src = "http://b.ceshi.com";
document.body.appendChild(iframe);

//判断是否加载完成
//iframe取值方法可根据name或者id但各个浏览器均有不同为了兼容IE/FF/Chrome方法如下
//统一使用iframe的id进行取值 document.getElementById('iframe_id').contentWindow.document.body.innerHTML
if (iframe.attachEvent){    //ie
    iframe.attachEvent("onload", function(){ 
        alert("Local iframe is now loaded."); 
        alert(iframe.contentWindow.document.body.innerHTML)
        document.getElementById('box1').innerHTML = iframe.contentWindow.document.body.innerHTML;
    }); 
} else { 
    iframe.onload = function(){ //chrome/ff
        alert("Local iframe is now loaded."); 
        alert(iframe.contentWindow.document.body.innerHTML)
        document.getElementById('box1').innerHTML = iframe.contentWindow.document.body.innerHTML;
    }; 
}
</script>
</body>
</html>

 

 

b.ceshi.com页面

<!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" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>ceshi2</title>
</head>
<body>
    我是2
<script type="text/javascript">
//设置主域
document.domain = 'ceshi.com';
</script>
</body>
</html>

 

这样就可以从a.ceshi.com读取到b.ceshi.com的内容了。

 

至于通过iframe跨不同主域名的,待续。。。