培训第2个月的第17天----ajax传值

                今天呢,主要是将一个功能进行实现。我们可以先看一下下面的图片:

                 今天就是将这个页面的标红部分进行实现。

一.实现的功能

                 如图标红部分是一个添加角色的功能,所以呢,我们需要用ajax来查询数据库中是否存在要添加的角色名,注意,这里的ajax使用的是同步(由于使用flag标记的原因)。

                 然后就是把下拉框自动填充和将满足要求的角色添加到数据库中。

二.action代码

                 实现上述的功能,我们需要编写两个action来处理,一个action是用来验证数据库中是否已经存在角色名,另一个则是将数据添加到数据库中。

     1.验证action:

package com.limit.emp.action;

import com.base.abstractclass.BaseAction;
import com.limit.role.bean.T_limit_Role;
import com.limit.role.dao.RoleInterface;

public class CheckRoleIsExistAction extends BaseAction<T_limit_Role>{
    
	//用于模型驱动的对象
	T_limit_Role t_limit_Role=new T_limit_Role();
	
	//service层的对象
	RoleInterface service=new RoleInterface();
	
	
	@Override
	public T_limit_Role getModel() {
		// TODO Auto-generated method stub
		return t_limit_Role;
	}

	@Override
	public String execute() {
	System.out.println("进入 CheckRoleIsExistAction ");
	System.out.println(t_limit_Role.getName());
	T_limit_Role result=service.checkRole(t_limit_Role);
	//说明用户存在
	if(result!=null) {
		this.addActionError("no add");
	}else {
		this.addActionMessage("yes add");
	}
		return INPUT;
	}
    
}

                    代码中,由于我们实现了ModelDriven接口,所以我们使用模型驱动来接收前台传递过来的数据。这里就是将接收到的对象当做参数进行一次数据库的查询,并且,如果查询到了,那么就像request对象中存放addActionError信息(addActionError信息其实就是以固定·的key值存放在request对象中的值,它以集合的形式存在)。如果没查询到那么就向request的对象中存放addActionMessage(addActionMessage和addActionError道理相同,只是所访问的key值不同)。

                      在执行完action后,用return返回值的方式跳转到message.jsp页面(跳转的方式默认为请求转发)。并且,由于使用请求转发来跳转页面,所以在message.jsp页面中,我们可以取出存放在request对象中值(由于是一个对象):

 

 2.添加action

          添加操作,我们只需要将前台传递过来的值,插入到数据库中即可。

package com.limit.emp.action;

import java.util.Date;

import com.base.abstractclass.BaseAction;
import com.limit.role.bean.T_limit_Role;
import com.limit.role.dao.RoleInterface;

public class AddRoleAction extends BaseAction<T_limit_Role> {
	
	//service层的对象
	RoleInterface service= new RoleInterface(); 

    //用来模型驱动的对象
	T_limit_Role t_limit_Role=new T_limit_Role();
	
	
	@Override
	public T_limit_Role getModel() {
		// TODO Auto-generated method stub
		return t_limit_Role;
	}

	@Override
	public String execute() {
		t_limit_Role.setOperateTime(new Date());
		t_limit_Role.setOperator(1);
		t_limit_Role.setValid(1);
		//向数据库中插入数据(role)的方法
		boolean result = service.addRole(t_limit_Role);
		if(result==true) {
			System.out.println("添加角色成功");
		}else {
			System.out.println("添加角色失败");
		}

		return "manageT_limit_Role";
	}
	
	public static void main(String[] args) {
		AddRoleAction a=new AddRoleAction();
		a.execute();
	}

}

                  这里同样的使用模型驱动来接收前台传递过来的参数,使用模型驱动,是不需要为模型提供get,set方法的。

三.前台页面ajax

                  后台的action代码写完之后,我们需要前台向后台来传递值。而传值的方式来我们校验角色名是否在数据库中时,使用ajax,而在保存数据的时候,我们使用表单提交按钮来实现。

<%@page import="com.base.util.TurnPage"%>
<%@page import="com.base.util.SessionTools"%>
<%@page import="com.limit.emp.dao.EmpInterface"%>
<%@page import="com.base.util.StringTools"%>
<%@page import="com.base.statics.YesNoType"%>
<%@page import="com.base.util.DateTools"%>
<%@page import="com.limit.role.bean.T_limit_Role"%>
<%@page import="com.limit.role.dao.T_limit_RoleDao" %>
<%@page import="com.limit.role.dao.RoleInterface"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
%>
<!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>
		<link href="../../skin/css/style.css" rel="stylesheet" type="text/css" />
		<title>menu</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8;" />
		<script language='javascript'>var curopenItem = '1';</script>
		<script language="javascript" type="text/javascript" src="<%=path %>/js/jquery.min.js"></script>
		<script language="javascript" type="text/javascript" src="<%=path %>/js/JSTools.js"></script>
		<%@include file="/js/jquery-ui.jsp" %>
		<base target="main" />
		<script type="text/javascript">
		
		</script>
		<jsp:include page="/validMessage_decode.jsp"></jsp:include>
		
		<!-- 表单的提交和验证 -->
		<script>
		    //进行页面加载事件
            $(function(){
            	$("#name").blur(function(){
            		
            		 checkRoleName();
            	});
            	
            	$("#btnAddRole").click(function(){
            		//进行提交前验证,调用这个方法
            		var con1=checkRoleName();
            		//是数字
            		var con2=!isNaN($("#selPid option:selected").val());
            		if(con1 && con2 ){
            			$("#formAddRole").submit();
            		}else{
            			$.alert("提交失败");
            		}
            	});
            	
            });

             function checkRoleName(){
            	 var name=$("#name").val();
            	 //不能将a转换正int类型
            	 // var id=$("#selPid option:selected").val();
            	 var flag=false;
            	 /*进行验证*/
            	 $.ajax({
            		 //需要传入的参数
            		 data:{"name":name}, //  ,"pid":id
            		 url:'<%=path%>/checkRoleIsExistAction.action',
            		 async:false,
            		 dataType:"json",
            		 success:function(req){
            			 alert(JSON.stringify(req));
            			 $("#roleMessege").html(req.data.value);
            			 if(req.data.key.trim()=="success"){
            				 flag=true;
            			 }
            			 if(req.data.key.trim()=="error"){
            				 flag=false;
            			 }
            		 },
            		 error:function(){
            			 alert("action 执行失败了");
            		 }
            		
            		 
            	 });
            	 return flag;
             }
        //----------------------------------------------------------------------------------------------------------------------------
        
        $(function(){
        	
        });
        
        function queryRole(){
        	//ajax查询
        	$.ajax({
        		url:'<%=path%>/queryRoleBean.action',
        		async:false,
        		
        		
        	});
        }
        </script>
	</head>
	<body leftmargin="8" topmargin="8">
		<!-- 弹出层 开始 -->
		<center>
		<div id="d1" style="display:none;width:97%;height:97%;position:absolute;z-index:100;background-color:white;margin:0 0 0 0px;filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;">
	 		<!-- <div id="d2" style="border: 0px solid blue;margin:10% 0 0 20%; width:50%;height:400px; background-color: #EAE8E4;"> -->
		 	<!-- </div> -->
	 	</div>
 		<div id="d2" style="display:none;border: 0px solid green;margin:15% 0 0 15%; width:70%;height:50%;z-index: 101;position: absolute;">
 		</div>
 		<div id="d3" style="display:none;border: 0px solid red;z-index: 102;position:absolute;margin:16% 0 0 65%;" align="right">
 			<a href=" javascript:void(0);" id="closeDIV">关闭</a>
 		</div>
		</center>
		<!-- 弹出层 结束 -->
		<!-- 标题 -->
        <div  class="wdjh_b" style=" padding-left:1%; width:98%">
		<table width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="" align="center">
			<tr>
				 <td height="26" align="center"><br /><h1 style=" color:#226411;">添加角色</h1></td> 
			</tr>
		</table>
		<!-- 添加角色表单 -->
		<table width='100%'  border='0' align="center" style="margin-top:8px">
		  <tr>
		    <td align='center'>
				    <!-- 添加角色表单 -->
				    <form id="formAddRole" action="addRoleAction.action" method="post">
				      <table border='0' cellpadding='5' cellspacing='0' style="margin-top: 10px;">
					        <tr>
						        <td width='170px' align="right">角色名:</td>
						        <td width='170px'>
						          	<input type='text' id="name" name='name' value='' style='width:150px' />
						        </td>
						        <td width="10px">&nbsp;
						        	<span id="roleMessege"></span>
						        </td>
						     </tr>
						     <tr>    
						        <td align="right">所属上级角色名:</td>
						        <td>
						        <%
						        	/*查询所有的角色*/
						        	T_limit_RoleDao t_limit_RoleDao=new T_limit_RoleDao();
					                List<T_limit_Role> list=t_limit_RoleDao.selectAllRole();
						        
						        %>
						          	<select id="selPid" name="pid" style="width: 155px;">
						          		<option value="a">请选择角色</option>
						          		<% 
						          		   for(T_limit_Role t:list){ 
						          		
						          		%>
						          		<option value="<%= t.getId()%>">
						          		     <%=
						          		    		t.getName()
						          		     %>
						          		</option>
						          		
						          		
						          		<% 
						          		   }
						          		%>
						          		
						          		
						          		
						          		
						          		<option value="0">-- 顶级角色 --</option>
						          	</select>
						        </td>
						        <td>&nbsp;
									<span id="roleRightMessege"></span>
						        </td>
					       </tr>
					       <tr>
					       		<td colspan="3" align="center" height="50px">
						          <input type="button" id="btnAddRole" value="添加"/> 
					       		</td>
					       </tr>
				      </table>
			      </form>
		    </td>
		  </tr>
		</table>
		<!-- 标题 -->
		<table width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="" align="center">
			<tr>
			 	<td height="26" align="center"><br /><h1 style=" color:#226411;">管理角色</h1>
				 </td>
			</tr>
		</table>
		
		  <form name="form1" id="form1" method="post" action="manageT_limit_Role.jsp">
		  <table width="98%" border="0" cellpadding="2" align="center" style="margin-top:8px">
		  	<tr>
		  		<td align="center">角色名:<input type="text" name="roleName" id="txtRoleName" value="">&nbsp;<input type="submit" name="sub" id="sub" value="查询" class="button"></td>
		  	</tr>
		  </table>
		  </form>
		  <div class="wdjh_b">
		
		<!--  内容列表   --> 
        <table width="100%" border="0" cellpadding="2" cellspacing="1" bgcolor="#D1DDAA" align="center" style="margin-top:8px;">
			<tr bgcolor="#FFFFFF" class="wdjh_ba">
				<td height="40" colspan="7" style="text-align:center;">&nbsp;角色列表&nbsp;</td>
			</tr>
			<tr align="center" bgcolor="#E7E7E7" class="wdjh_ba">
				<td width="5%">序号</td>
				<td width="20%">角色名</td>
				<td width="20%">所属上级角色名</td>
				<td width="5%">生效状态</td>
				<td width="10%">操作时间</td>
				<td width="10%">操作人</td>
				<td width="">操作</td>
				
			</tr>
			<% 
			   EmpInterface service=new EmpInterface();
			   List<Map> list1=service.queryRole();
			%>
			<%
			   for(Map map:list1){
				   //for(Object obj:map.keySet()){
				 
			%>
			<tr align='center' bgcolor="#FFFFFF" onMouseMove="javascript:this.bgColor='#FCFDEE';" onMouseOut="javascript:this.bgColor='#FFFFFF';">
				<td><%= map.get("id")%></td>
				<td><%= map.get("name")%></td>
				<td><%= map.get("pname")%></td>
				<td><%= map.get("valid")%></td>
				<td><%= map.get("operateTime")%></td>
				<td><%= map.get("operator")%></td>
				<td>
					<a id="modiRole" href="" onclick="">修改</a> | 
					<a href="" onclick="return del()">删除</a> | 
					<a href="">设置</a> |  
					<a href=""></a>
					</a>
				</td>
			</tr>
			<%
			 //  }
				   }
			%>
		</table> 
		<center>
	        <div class="ym width_">
	        	
	        </div>
		</center>
        </div>   
	</body>
</html>

                现在我们来简单的看一下上面的代码,我们首先定义了一个 checkRoleName()方法,用ajax来传递数据(这里使用的是同步,而不是异步),使用同步的原因是设立一个标记flag来确实用户是否可以提交表单。

                 总的来说,用ajax传值是很棒的一个选择,但是我的ajax真的不敢恭维。。。。。。。

猜你喜欢

转载自blog.csdn.net/qq_41160264/article/details/82595280