导语:
在实际开发过程中经常会遇到一些跨域问题,如通过iframe嵌入一个跨域的页面。这个问题也是在面试时,那些项目经理经常喜欢提及的,因此做一个小Demo以供大家参考。
首先创建一个远程服务器上的页面test.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>远程页面</title>
<script type="text/javascript">
function f1() {
var userName = document.getElementById("userName");
var pwd = document.getElementById("pwd");
var btnAlert = document.getElementById("btnAlert");
btnAlert.onclick = function () {
if (userName.value == "china" && pwd.value == "china") {
alert("登录成功");
} else {
alert("登录失败");
}
}
}
window.onload = function () {
document.getElementById("btnF2").onclick = function () {
window.parent.f2();
};
f1();
}
function f3() {
alert("远程服务器上f3函数执行成功");
}
</script>
</head>
<body>
用户名:<input type="text" id="userName" /><br />
密码:<input type="text" id="pwd" /><br />
<input type="button" value="提交" id="btnAlert" /><input type="button" id="btnF2" value="调用父级页面中的f2方法" />
</body>
</html>
本地的页面parent.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>本地页面</title>
<script type="text/javascript">
window.onload = function () {
//获得Iframe的顶级节点window
var country = document.getElementById("country").contentWindow;
//获得iframe中的两个文本框
var userName = country.document.getElementById("userName");
var pwd = country.document.getElementById("pwd");
var btnLogin = document.getElementById("btnLogin");
//操作远程页面中的登录
btnLogin.onclick = function () {
if (userName.value == "china" && pwd.value == "china") {
alert("登录成功");
} else {
alert("登录失败");
}
}
//调用远程页面的f3方法
document.getElementById("btnF3").onclick = function () {
country.f3();
};
}
function f2() {
alert("iframe中远程服务器页面调用父级页面中的函数成功");
}
</script>
</head>
<body>
<iframe id="country" name="cc" src="http://www.chinatt315.org.cn/2010315tps/test.html"></iframe>
<input type="button" value="调用远程页面的f3方法" id="btnF3" /><br />
<input type="button" value="操作远程页面中的登录" id="btnLogin" />
</body>
</html>
总结:在本地获得远程页面的顶级元素window是一个关键document.getElementById("iframeId").contentWindow,远程页面获得其父页面的window对象也是一个关键点window.parent,然后其他的编程与平常的编程没有什么异样。