需求:主域页面(https://www.temp.org/test.html)发起ajax请求获取二级域名页面(https://test.temp.org/test2.html)内容
初始错误做法:
$.ajax({
type:"post",
url:"https://test.temp.org/test2.html",
success:function(data){
var temp=$(data).find(".focus_news");
$(temp).appendTo('.txt')
}
})
错误原因解析:
主域页面(https://www.temp.org/test.html)发起ajax请求获取二级域名页面(https://test.temp.org/test2.html)内容,也因受到同源策略(Same Origin Policy)的限制,无法正常使用ajax请求!
解决方法:
主域名及二级域名页面都加上document.domain = 'temp.org';使俩文档web服务器的主机名一致,再用"创建一iframe标签引入二级域名页面,再读取该iframe页面对应标签内容"的方法代替之前的ajax请求
具体完整代码:
document.domain = 'temp.org';
var ifr = document.createElement('iframe');
ifr.src = 'https://test.temp.org/test2.html';
$(ifr).appendTo("body").hide();
ifr.onload = function(){
// contentDocument: 标准写法,用于获取iframe页面document对象,但ie7不支持
// contentWindow.document:非标准写法,但各浏览器都兼容,.contentWindow获取的是window对象,固还要加.document以获取iframe页面document对象
var doc = ifr.contentDocument || ifr.contentWindow.document;
// alert(doc);
var temp=$(doc).contents().find(".notice");//jq1.9前必须加.contents()(该方法常用于iframe页面内容的引用),加了contents()方法,ie7下才能获取iframe页面的内容!
$(temp).appendTo('.txt');
};
注释部分是用法解析,是重点!!
请按各自需要,自行挖掘代码精粹部分,呵.。。。