html页面,有的时候不是直接一个页面,一连串(或并行)页面的结束,为了提高用户体验或完成某种功能需要父子页面(或窗口)来实现,或者父子,兄弟窗口来完成。本文主要介绍:
html父子页面(弹框)的实现和交互[通信]
实现简单业务介绍:
1.父页面,点下“注册”按钮,按钮锁定,并弹框;
2.父页面隐藏域的值“欢迎您的注册……”,传给子弹框,并显示;
3.子窗口,进行注册用户,成功后调用父页面js方法,将注册的“用户名”填写到登录用户名中;
4.用户登录,后台ajax传值,显示注册的“用户名”;
5.后台类的处理,使用MAP保存[内存暂时],然后用用户名去获取对象进行登录验证。
父页面jsp代码[popupmain.jsp]:
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>注册页面</title> <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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript" src="${pageContext.request.contextPath }/tsjs/jquery-1.11.1.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath }/tsjs/popupmain.js"></script> </head> <body> <center id="centerid"> <div id="userlogin"> <form id="userloginform"> <table id="tbuserlogin" width="150" border="0" cellpadding="0" cellspacing="0"> <tr class="setshow"> <td width="30">user:</td> <td width="70"> <input id="userlog" name="userlog" type="text" maxlength="8" size="15" /> </td> <td width="50"><div id="userlogmsg"></div></td> </tr> <tr class="setshow"> <td width="30">pass:</td> <td width="70"> <input id="passlog" name="passlog" type="password" maxlength="12" size="15" /> </td> <td></td> <td></td> </tr> <tr> <td colspan="2" align="right"> <div id="userregbtdiv"> <input type="button" id="popupbt" value="注册" /> </div> <div id="userloginbtdiv"> <input type="button" id="userlogin" value="登录" onclick="login(this);" /> </div> </td> </tr> </table> </form> </div> </center> <input id="contextPath" type="hidden" value="${pageContext.request.contextPath }"> <!-- 子窗口 -> 父页面的交互传值[到] --> <input id="returnreginfo" type="hidden" value=""> <!-- 父页面 -> 子窗口的交互传值 --> <input id="maintochildwidow" type="hidden" value="欢迎您的注册……"> </body> </html>
父页面的js[popupmain.js]:
$(document).ready(function() { var contextPath = $("#contextPath").val(); $("tr[class='setshow']").hide(); $("#userloginbtdiv").hide(); $("#popupbt").click(function(){ //锁定注册按钮 $("#popupbt").attr("disabled",true); //弹框的url var popup_url = contextPath+"/tsjsp/popup.jsp"; //弹框高度 var popup_height = "350"; //弹框宽度 var popup_width = "500"; //获得窗口的垂直位置 var popup_top_dist = (window.screen.availHeight - 30 - popup_height) / 2; //获得窗口的水平位置 var popup_left_dist = (window.screen.availWidth - 10 - popup_width) / 2; //打开连接弹框界面 winOpen = window.open(popup_url,'newwindow','width='+popup_width+',height='+popup_height+',top='+popup_top_dist+',left='+popup_left_dist+',toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no'); //检查是否关闭新窗口,1s一次 winOpenClosedShow();//window.onload window.setInterval("winOpenClosedShow()",1000); }); }); function login(obj){ var value = obj.value; var id =obj.id; // alert(value+"*"+id); $("#userlogin").attr("disabled",true); $.ajax({ url:"user.do?param=login", type:"post", data:$("#userloginform").serialize(), timeout:20000, success:function(data){ $("#centerid").html("<div style=\"color: #0F0;\">"+data+"欢迎您登录...<div>"); }, error:function(){ alert("您登录失败,请重新登录"); } }); } //弹框关闭,用户进行登录 function winOpenClosedShow(){ if(!winOpen || winOpen.closed){ $("#popupbt").attr("disabled",false); $("#userregbtdiv").hide(); $("tr[class='setshow']").show(); $("#userloginbtdiv").show(); } } function setUser(){ setTimeout(function(){ var returnreginfo = $("#returnreginfo").val(); $("#userlog").val(returnreginfo); },1000); }
注:获取当前的操作this下的obj对象[参数]的属性:
1.var id = $(obj).attr("id"); var id = $(obj).val();
2.var id =obj.id; var value = obj.value;
注:setTimeout(A,B);是属于 window 的 method, 但我们都是略去 window 这顶层物件名称, 这是用来设定一个时间, 时间到了, 就会执行一个指定的 method
A为要执行的代码,字符,函数等都可以,B为定时时间,单位为ms[毫秒]
注:window.open();
环境:JavaScript1.0+/JScript1.0+/Nav2+/IE3+/Opera3+
语法:window.open(pageURL,name,parameters)
pageURL为子窗口路径;name为子窗口句柄;parameters为窗口参数(各参数用逗号分隔)
参数|取值范围|说明:其中yes/no也可使用1/0;pixelvalue为具体的数值,单位像素。
alwaysLowered | yes/no | 指定窗口隐藏在所有窗口之后 alwaysRaised | yes/no | 指定窗口悬浮在所有窗口之上 depended | yes/no | 是否和父窗口同时关闭 directories | yes/no | Nav2和3的目录栏是否可见 height | pixelvalue | 窗口高度 hotkeys | yes/no | 在没菜单栏的窗口中设安全退出热键 innerHeight | pixelvalue | 窗口中文档的像素高度 innerWidth | pixelvalue | 窗口中文档的像素宽度 location | yes/no | 位置栏是否可见 menubar | yes/no | 菜单栏是否可见 outerHeight | pixelvalue | 设定窗口(包括装饰边框)的像素高度 outerWidth | pixelvalue | 设定窗口(包括装饰边框)的像素宽度 resizable | yes/no | 窗口大小是否可调整 screenX | pixelvalue | 窗口距屏幕左边界的像素长度 screenY | pixelvalue | 窗口距屏幕上边界的像素长度 scrollbars | yes/no | 窗口是否可有滚动栏 titlebar | yes/no | 窗口题目栏是否可见 toolbar | yes/no | 窗口工具栏是否可见 Width | pixelvalue | 窗口的像素宽度 z-look | yes/no | 窗口被激活后是否浮在其它窗口之上
子窗口jsp代码[popup.jsp]:
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>用户注册界面</title> <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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript" src="${pageContext.request.contextPath }/tsjs/jquery-1.11.1.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath }/tsjs/popup.js"></script> </head> <!-- overflow:滚动条 --> <body id="bodyid" style="overflow: scroll;"> <center id="centerid"> <!-- 欢迎语显示 --> <div id="welcomto"></div><br /> <div id="userreg"> <form id="userregform"> <table id="tbuserreg" width="150" border="0" cellpadding="0" cellspacing="0"> <tr> <td width="30">user:</td> <td width="70"> <input id="userreg" name="userreg" type="text" maxlength="8" size="15" /> </td> <td width="50"><div id="userregmsg" style="color: red;"></div></td> </tr> <tr> <td width="30">pass:</td> <td width="70"> <input id="passreg" name="passreg" type="password" maxlength="12" size="15" /> </td> <td></td> </tr> <tr> <td width="30">name:</td> <td width="70"> <input id="namereg" name="namereg" type="text" maxlength="12" size="15" /> </td> <td></td> </tr> <tr> <td colspan="2" align="right"> <input id="regbt" name="regbt" type="button" value="reg"> </td> </tr> </table> </form> </div> </center> </body> </html>
子窗口js代码[popup.js]:
$(document).ready(function(){ //window.opener表示打开子窗口的父(主)页面 var parentHtml = window.opener; //父页面给子页面传值,也可以用url传参 eg:"url?id="+id; 父 -> 子[交互] if(parentHtml != null){ var wlstr = parentHtml.document.getElementById("maintochildwidow").value; $("#welcomto").html("<span style=\"color:blue;\">"+wlstr+"</span>"); } //获取弹框页面内容的高度 var htmlheight = document.body.clientHeight; //获取弹框页面内容的宽度 var htmlwidth = document.body.clientWidth; //用户内容大小,大于弹框大小,显示滚动条 // alert(htmlheight+"*"+htmlwidth); if(htmlheight < 350){ $("#bodyid").css("overflow-y","hidden"); } if(htmlwidth < 500){ $("#bodyid").css("overflow-x","hidden"); } if(htmlheight <= 350 && htmlwidth <= 500){ $("#bodyid").css("overflow","hidden"); } //注册 $("#regbt").click(function(){ $("#regbt").attr("disabled",true); $.ajax({ url:"user.do?param=reg", type:"post", data:$("#userregform").serialize(), timeout:20000, success:function(data){ //保存后台返回数据到父界面popupmain.jsp 子 -> 父[交互] window.opener.document.getElementById("returnreginfo").value = data; //调用父界面的js方法,setUser(),自动填写用户名 window.opener.setUser(); //关闭弹框子界面 window.close(); }, error:function(){ $("#centerid").html("<div style=\"color: red;\">不好意思,由于……,您注册失败,请关闭页面,点击重新注册...<div>"); } }); }); });
struts1configuration[struts-config.xml]配置:
<action path="/user" parameter="param" scope="request" type="com.ts.actions.UserRegAndLoginAction"> <forward name="success" path="/tsjsp/popupmain.jsp"></forward> </action>
后台处理类[UserRegAndLoginAction]:
package com.ts.actions; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; /** * ClassName: UserRegAndLoginAction <br/> * Description: TODO <br/> * Date: 2015-1-22 下午05:09:23 <br/> * <br/> * * @author yptian@aliyun.com * * first made * @version 0.0.1<br/> * */ public class UserRegAndLoginAction extends DispatchAction { private static final Logger LOG = Logger.getLogger(UserRegAndLoginAction.class); //db private static Map<String, User> userMap = new HashMap<String, User>(); //reg public ActionForward reg(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String userId = request.getParameter("userreg"); String userPass = request.getParameter("passreg"); String userName = request.getParameter("namereg"); User user = new User(); user.userId = userId; user.userPass = userPass; user.userName = userName; userMap.put(userId, user); LOG.info("user reg:"+userId+"***"+userPass+" - "+userName); response.setHeader("Cache-Control", "no-cache"); response.setContentType("text/html"); response.setCharacterEncoding("GBK"); PrintWriter out = response.getWriter(); out.print(userId); out.close(); return null; } //login public ActionForward login(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String userId = request.getParameter("userlog"); String userPass = request.getParameter("passlog"); User user = userMap.get(userId); LOG.info("user reg:"+user.userId+"***"+user.userPass); LOG.info("user login:"+userId+"***"+userPass); if(userId.equals(user.userId) && userPass.equals(user.userPass)){ response.setHeader("Cache-Control", "no-cache"); response.setContentType("text/html"); response.setCharacterEncoding("GBK"); PrintWriter out = response.getWriter(); out.print(user.userName); out.close(); } return null; } //vo class User{ public String userId; public String userPass; public String userName; } }
系列效果图: