1、首先:搭建开发环境在MyEclipse中创建一个Java Web项目,并导入jQuery运行库:
2、处理业务创建一个子页面:children_page.jsp:<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
3、<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>子页面</title>
4、<meta http-equiv="pragma"content="no-cache"> <meta http-equiv="cache-control"content="no-cache"> <meta http-equiv="expires"content="0"> <meta http-equiv="keywords"content="keyword1,keyword2,keyword3"> <meta http-equiv="description"content="This is my page"> </head>
5、<body> <p>嵌套的iFrame页面</p> 请输入一些值:<input type="text"id="someValue"/> <button onclick="transfer();">开始传值</button> <script type="text/javascript"src="jquery.js"></script> <script type="text/javascript">
6、functiontransfer(){ $('#transferValue', parent.document).attr("value",$("#someValue").val()); } </script> </body></html>
7、创建一个父页面:Index.jsp:<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
8、<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>iFrame子父页传值页面</title>
9、<meta http-equiv="pragma"content="no-cache"> <meta http-equiv="cache-control"content="no-cache"> <meta http-equiv="expires"content="0"> <meta http-equiv="keywords"content="keyword1,keyword2,keyword3"> <meta http-equiv="description"content="This is my page"> </head>
10、<body> <div style="margin:0px auto; width:300px;"> iFrame传过来的值:<input id="transferValue"/> </div>
11、<div style="margin:20px auto; width:300px;"> <iframe src="children_page.jsp"width="300"height="100"frameborder="1"scrolling="auto"></iframe> </div> </body></html>
12、注意:关键点在这里:$('#transferValue', parent.document).attr("value",$("#someValue").val());# transferValue 表示父页面中传值的目标,即要把值传到哪一个元素上面;parent.document()指定了要操作的document对象,这里指定为当前页面的父页面;attr()中的参数1 表示父页面中传值目标的属性,这里传值目标元素是文本框,所以直接设置它的value属性就可以赋值;attr()中的参数2表示子页面要传的值的来源,即要把什么值传递到父页面。如果子页面使用Ajax操作业务逻辑,那么就特别适用于这样的场景。效果展示未传值:
13、在iFrame中填写了“Hello,Steve Jong!”后,点击按钮,把值传递到了父页面的文本框中: