大家好,对jQuery 浅析iframe来解决跨域的简单示例(1)感兴趣的小伙伴,下面一起跟随三零脚本的小编来看看jQuery 浅析iframe来解决跨域的简单示例(1)的例子吧。
跨域的解决方案有许多种,就不一一介绍了,在这里主要总结一下用iframe来解决跨域的方法。
/**
* iframe来解决跨域
*
* @param
* @arrange (三零脚本) www.q3060.com
**/
var iframe1 = document.createElement("iframe");
iframe1.src = "http://127.0.0.1/server.html";
(function() {
// 当iframe加载完之后触发的函数
function iframe1_load() {
}
// 在IE下要用attachEvent来添加iframe的onload事件
if(iframe1.attachEvent) {
iframe1.attachEvent("onload", function(){
iframe1_load();
});
}
else {
iframe1.onload = iframe1_load;
}
})();
document.body.appendChild(iframe1);
注意这里的iframe1_load函数,它在iframe1完全加载完之后被浏览器调用,我们在这里取回从服务器返回的数据。上面说过,从服务器返回的数据应该是保存在window.name里的,改写一下iframe1_load:
/**
* iframe来解决跨域
*
* @param
* @arrange (三零脚本) www.q3060.com
**/
function iframe1_load() {
alert(iframe1.contentWindow.name);
}
但由于同源策略的原因,上面的语句会报错,因为iframe1访问的页面在http://127.0.0.1/这个域,而这上面的JavaScript所在的页面是在http://localhost/,所以client.html暂时还不能访问iframe1的大部分属性。这个时候聪明的同学就能想到,如果把iframe1导航到http://localhost/下面的页面不就可以访问window.name了吗?而且上面也说过window.name在换了页面之后,还是存在的。
/**
* iframe来解决跨域
*
* @param
* @arrange (三零脚本) www.q3060.com
**/
var iframe1 = document.createElement("iframe");
iframe1.style.display = "none";
document.body.appendChild(iframe1);
(function () {
var same_domain = false;
// 当iframe加载完之后触发的函数
function iframe1_load() {
if (same_domain) {
// 取得从服务器返回的数据
alert(iframe1.contentWindow.name);
// 关闭iframe1的窗口
iframe1.contentWindow.close();
// 移除iframe1
document.body.removeChild(iframe1);
} else {
same_domain = true;
// 不能用iframe1.src = "empty.html",在IE下有错误
iframe1.contentWindow.location = "empty.html";
}
}
// 在IE下要用attachEvent来添加iframe的onload处理函数
if (iframe1.attachEvent) {
iframe1.attachEvent("onload", function () {
iframe1_load();
});
}
else {
iframe1.onload = iframe1_load;
}
})();
iframe1.src = "http://127.0.0.1/server.html";
server.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>
<title>Server</title>
<script type="text/javascript">
window.name = "HELLO WORLD";
</script>
</head>
<body>
</body>
</html>