Struts2.2配置json+ajax实现三级联(任意级联)下拉列表框。

前言:在网上找了一些相关资料,选择了一个方式应用到自己的SSH框架中,遇到了很多困难(主要是后台没写好),折腾了两天终于实现了ajax的局部刷新功能,万法归一,像登录校验,刷新table等功能都可以用这种方式,多了不说上代码。

1.action类:

	private String id="";
	private String schoolId;
	private String name="";
	private String classId;
	private String code=null;
    private GangedService gangedService;
    
	public GangedService getGangedService() {
		return gangedService;
	}
	public void setGangedService(GangedService gangedService) {
		this.gangedService = gangedService;
	}
	public String queryAllSchool() throws Exception{
		//List schoolList = new CascadeMenuDAO().findAllSchool();
		List<School> schoolList = this.gangedService.findAllSchool();
		// 写入到被前台页面接收的字符串,id和name以_隔开 以"school"结尾
		for (int i = 0; i < schoolList.size(); i++) {
			School school = (School) schoolList.get(i);
			id += school.getId() + "_";
			name += school.getName() + "_";
		}
		code = id + "|" + name + "|school";
		//System.out.println(code);
		return ActionSupport.SUCCESS;
		//return SUCCESS;
	}
	public String queryAllClass() throws Exception{
		id="";name="";
		int sId = Integer.parseInt(schoolId);// 把从前台传来的参数转换成int类型的
		//List schoolList = new CascadeMenuDAO().findClassbySchoolid(sId); // 写入到被前台页面接收的字符串,id和name以_隔开
		List<Class1> classList = this.gangedService.findClassBySchoolId(sId);// 以"class"结尾
		System.out.println("hah");
		for (int i = 0; i < classList.size(); i++) {
			Class1 class1 = (Class1) classList.get(i);
			id += class1.getId() + "_";
			name += class1.getName() + "_";
		}
		code = id + "|" + name + "|class";
		System.out.println(code);
		return ActionSupport.SUCCESS;
		//return SUCCESS;
	}

	public String queryAllStudent() {
		id="";name="";
		int cId = Integer.parseInt(classId);

		//List schoolList = new CascadeMenuDAO().findStubyclassId(cId); // 写入到被前台页面接收的字符串,id和name以_隔开
		List<Student> studentList = this.gangedService.findStudentByclass(cId);																// 以"student"结尾
		for (int i = 0; i < studentList.size(); i++) {
			Student student = (Student) studentList.get(i);
			id += student.getId() + "_";
			name += student.getName() + "_";
		}
		code = id + "|" + name + "|student";
		//return ActionSupport.SUCCESS;
		return SUCCESS;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getSchoolId() {
		return schoolId;
	}

	public void setSchoolId(String schoolId) {
		this.schoolId = schoolId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getClassId() {
		return classId;
	}

	public void setClassId(String classId) {
		this.classId = classId;
	}

	@JSON(name="code")
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

dao层:

public List<School> findAllSchool() {
		// TODO Auto-generated method stub
	HibernateTemplate ht = this.getHibernateTemplate();
	String hql = "from School s order by s.id asc";
	///from User u order by u.id asc
	@SuppressWarnings("unchecked")
	List<School> schoollist = ht.find(hql);
    for(School school1:schoollist){  
    	school1.getName();
    } 
		return schoollist;
	}

	@Override
	public List<Class1> findClassBySchoolId(int schoolId) {
		// TODO Auto-generated method stub
		HibernateTemplate ht = this.getHibernateTemplate();
		String hql = "from Class1 where school_id = '"+schoolId+"'";
		@SuppressWarnings("unchecked")
		List<Class1> classlist = ht.find(hql); 
		return classlist;
	}

	@Override
	public List<Student> findStudentByclass(int classId) {
		// TODO Auto-generated method stub
		HibernateTemplate ht = this.getHibernateTemplate();
		String hql = "from Student where class_id='"+classId+"'";
		@SuppressWarnings("unchecked")
		List<Student> studentlist = ht.find(hql);
		return studentlist;
	}

Struts.xml配置:

    <package name="ganged" extends="json-default">  
        <action name="allSchool" class="GangedAction" method="queryAllSchool"> 
            <result name="success" type="json">
                <param name="root">code</param> 
            </result>  
        </action>  
        <action name="allClass" class="GangedAction" method="queryAllClass">  
            <result name="success" type="json">
                <param name="root">code</param>
            </result>  
        </action>  
        <action name="allStu" class="GangedAction" method="queryAllStudent">  
            <result name="success" type="json">
                <param name="root">code</param>
            </result>  
        </action>  
    </package>  


前台ganged.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<base href="<%=basePath%>">
<title></title>

<script type="text/javascript">
	//创建XMLHttpRequest对象   
	function createXMLHttpRequest() {
		if (window.XMLHttpRequest)
		  {// code for all new browsers
			XMLHttpReq=new XMLHttpRequest();
			//return XMLHttpReq;
		  }
		else if (window.ActiveXObject)
		  {// code for IE5 and IE6
			XMLHttpReq=new ActiveXObject("Microsoft.XMLHTTP");
			//return XMLHttpReq;
		  }
		else
		  {
		  alert("Your browser does not support XMLHttpReq.");
		  }
		
	}
	//发送请求
	function sendRequest(url, params, method) {
		if (method) {
			if (method.toLowerCase("post")) {
				alert("post方法");
				sendRequestPost(url, params);
			} else {
				if (method.toLowerCase("get")) {
					sendRequestGet(url + "?" + params);
				} else {
					//
				}
			}
		} else {
			alert("\u63d0\u4ea4\u65b9\u5f0f\u4e0d\u80fd\u4e3a\u7a7a\uff01");
		}
	}
	//post发送请求函数
	function sendRequestPost(url, params) {
		createXMLHttpRequest();
		XMLHttpReq.open("POST", url, true);
		XMLHttpReq.onreadystatechange = processResponse;//指定响应函数
		XMLHttpReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		//XMLHttpReq.setRequestHeader("context-type","text/xml;charset=utf-8");
		XMLHttpReq.send(params); // 发送请求
	}
	//get发送请求函数
	function sendRequestGet(url) {
		createXMLHttpRequest();
		XMLHttpReq.open("GET", url, true);
		XMLHttpReq.onreadystatechange = processResponse;//指定响应函数
		XMLHttpReq.send(null); // 发送请求
	}
	//post发送请求函数(无需传递参数时)
	function sendRequestPostwihtnoArgs(url) 
	{
	    createXMLHttpRequest();
	    //var XMLHttpReq = createXMLHttpRequest();
	    //var XMLHttpReq=new XMLHttpRequest();
		XMLHttpReq.onreadystatechange = processResponse;//指定回调函数
		XMLHttpReq.open("POST", url, true);
		//XMLHttpReq.open("GET", url, true);
		XMLHttpReq.send(null); // 发送请求
	}
	// 更新列表框
	function update() { 
		//alert("---XMLHttpReq.responseText--"+XMLHttpReq.responseText);
		//alert("---NMB1--");
		var res = eval('('+XMLHttpReq.responseText+')');
		//var a= "1_2_|一中_二中_|school";
		var option = null;
		//var id_name_code = res.code.split("|");//拆分字符串,得到id与name(包括后缀字符串)的组合值
		//var id_name_code = a.split("|");//拆分字符串,得到id与name(包括后缀字符串)的组合值
		var id_name_code = res.split("|");//拆分字符串,得到id与name(包括后缀字符串)的组合值
		//alert("---NMB2--");
		var id_result = id_name_code[0];//得到id的组合值(所有的id,以_隔开)
		var name_result = id_name_code[1];//得到name的组合值(所有的name,以_隔开)
		var result = id_name_code[2]; //得到后缀名字符串
		//拆分以_隔开的字符串
		var id = id_result.split("_");
		var name = name_result.split("_");
		//window.alert("---"+id_result);
		if ("student" == result) {
			clearStudent();
			var studentId = document.getElementById("studentId");
			for ( var i = 0; i < id.length; i++) {
				option = new Option(name[i], id[i]);
				studentId.options.add(option);
			}
		}
		if ("class" == result) {
			alert("成功调用class");
			clearClass();
			var classesId = document.getElementById("classId");
			for ( var i = 0; i < id.length; i++) {
				option = new Option(name[i], id[i]);
				classesId.options.add(option);
			}
		}
		if ("school" == result) {
			//alert("---NMB3--");
			clearSchool();
			var schoolId = document.getElementById("schoolId");
			for ( var i = 0; i < id.length; i++) {
				option = new Option(name[i], id[i]);
				schoolId.options.add(option);
			}
		}
	}
	// 清除列表框
	function clearSchool() {
		var schoolId = document.getElementById("schoolId");
		while (schoolId.childNodes.length > 0) {
			schoolId.removeChild(schoolId.childNodes[0]);
		}
	}
	function clearClass() {
		var classesId = document.getElementById("classId");
		while (classesId.childNodes.length > 0) {
			classesId.removeChild(classesId.childNodes[0]);
		}
	}
	function clearStudent() {
		var studentId = document.getElementById("studentId");
		while (studentId.childNodes.length > 0) {
			studentId.removeChild(studentId.childNodes[0]);
		}
	}
	// 处理返回信息函数
	function processResponse() {
		//alert("--readyState---"+XMLHttpReq.readyState);
		//var XMLHttpReq=new XMLHttpRequest();
		if (XMLHttpReq.readyState == 4) { // 判断对象状态
		alert("--status---"+XMLHttpReq.status);
			if (XMLHttpReq.status == 200) { //信息已经成功返回,开始处理信息
				//alert("成功了!!!");
				update();
			} else { //页面不正常
				window.alert("未找到页面");
			}
		}
	}
	function findStubyClasslId() {
		var classId = document.frmMenu.classId.value;
		var sURL = "allStu";
		var method = "post";
		var sParams = "classId=" + classId;
		sendRequest(sURL, sParams, method);

	}
	function findClassbySchoolId() {
		var schoolId = document.frmMenu.schoolId.value;
		var sURL = "allClass";
		var method = "POST";
		var sParams = "schoolId=" + schoolId;
		sendRequest(sURL, sParams, method);	
	}

	function findAllSchool() {
		var sURL = "allSchool";
		sendRequestPostwihtnoArgs(sURL);
	}
</script>


</head>
<body onload="findAllSchool()">
		<form name="frmMenu">
			<br>
			<hr>
			<div align="center">
				信息查询
				<br>
				<br>
				<!--select name="schoolId" id="schoolId" onblur="findClassbySchoolId()"-->
				<select name="schoolId" id="schoolId" onchange="findClassbySchoolId()">
					<option selected value="">
					请选择学校
					</option>

				</select>

				<!--select name="classId" id="classId" onblur="findStubyClasslId()"-->
				<select name="classId" id="classId" onchange="findStubyClasslId()">
					<option selected value="">
						请选择班级
					</option>
				</select>
				<select name="studentId" id="studentId">
					<option selected value="">
						请选择学生
					</option>
				</select>
			</div>

		</form>
	</body>
</html>



表结构:

 

 

 

 

显示结果:



二.ajax里xmlHttp.open()方法post与get的区别  

2010-05-13 11:58:40|  分类: 默认分类 |  标签: |举报 |字号 订阅

  POST:用"POST"方式发送数据,可以大到4MB,在接收页面使用Request.Form["..."]获取
  GET:用"GET"方式发送数据,只能256KB,在接收页面使用Request.QueryString["..."]获取

///////////////////////////////////////////////////////////////////////////////////////////////////////////

  一般情况下,使用Ajax提交的参数多是些简单的字符串,可以直接使用GET方法将要提交的参数写到open方法的url参数中,此时send方法的参数为null。
例如 :
   var url = "login.jsp?user=XXX&pwd=XXX";
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
  此外,也可以使用send方法传递参数。使用send方法传递参数使用的是POST方法,需要设定Content-Type头信息,模拟HTTP POST方法发送一个表单,这样服务器才会知道如何处理上传的内容。参数的提交格式和GET方法中url的写法一样。设置头信息前必须先调用open方法。
  例如:
  xmlHttp.open("POST","login.jsp",true);
  xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
  xmlHttp.send("user="+username+"&pwd="+password);
  需要注意的是根据提交方式的不同,两种提交方式分别调用后台的doGet方法和doPost方法。


 

 

 

 

 

 

 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。