看网上JqueryAjax三级联动的例子讲不是很全,代码也给的不是很全,给初学者带来一定的难度。小弟自己写了一个,可能有些地方不是很好,希望大家能够提出建议。
用的是Hibernate+struts2写的。http://blog.csdn.net/luckey_zh/article/details/22995389
以代码来说话吧。
首先是index1.jsp页面
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%
- 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>Jquery-ajax三级联动</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">
-
- <script type="text/javascript" src="jquery-1.8.3.min.js"></script>
- </head>
- <script type="text/javascript">
- $(function(){
- $.ajax({
- type:"post",
- url:"province",
- dataType:"json",
- async:false,
- success:function(data){
- var pro=eval("("+data+")");
- for(var i=0;i<pro.length;i++){
- $(".province").append("<option value="+pro[i].id+">"+pro[i].province+"</option>");
- }
- }
- });
- });
-
- </script>
- <body>
- 省:<select name="province" class="province">
- <option value="0">==请选择==</option>
- </select>
- 市:<select name="city" class="city">
- <option>==请选择==</option>
- </select>
- 区:<select name="town" class="town">
- <option>==请选择==</option>
- </select>
- </body>
- <script type="text/javascript">
-
- $(".province").change(function(){
- var province_id=$(".province").val();
- //如果选择的是‘==请选择==’,不会执行去查找市,平且把已有的数据清空
- if($(".province").val()==0){
- $(".city option").remove();
- $(".city").append("<option value=0>==请选择==</option>");
- $(".town option").remove();
- $(".town").append("<option value=0>==请选择==</option>");
- return;
- }
- $.ajax({
- type:"post",
- //传一个省的id参数
- url:"city?province_id="+province_id,
- dataType:"json",
- async:false,
- success:function(city){
- var city=eval("("+city+")");
- for(var i=0;i<city.length;i++){
- $(".city").append("<option value="+city[i].id+">"+city[i].city+"</option>");
- }
- }
- });
- });
- //市下拉列表框发生改变时候的事件
- $(".city").change(function(){
- var city_id=$(".city").val();
- if($(".city").val()==0){
- $(".town option").remove();
- $(".town").append("<option value=0>==请选择==</option>");
- return;
- }
- $.ajax({
- type:"post",
- url:"town?city_id="+city_id,
- dataType:"json",
- async:false,
- success:function(town){
- var town=eval("("+town+")");
- for(var i=0;i<town.length;i++){
- $(".town").append("<option value="+town[i].id+">"+town[i].town+"</option>");
- }
- }
- });
- });
- </script>
- </html>
三个实体类:
1.Province实体类
- package cn.yo.entity;
-
- import java.util.HashSet;
- import java.util.Set;
-
- public class Province implements java.io.Serializable {
-
- private Integer id;
- private String province;
- private Set cities = new HashSet(0);
- //省略了get,set方法
2.City实体类
- package cn.yo.entity;
-
- import java.util.HashSet;
- import java.util.Set;
-
- public class City implements java.io.Serializable {
-
- private Integer id;
- private Province province;
- private String city;
- private Set towns = new HashSet(0);
- //省略了get,set方法
3.Town实体类
- package cn.yo.entity;
-
- public class Town implements java.io.Serializable {
-
- private Integer id;
- private City city;
- private String town;
- //省略了get,set方法
本人比较懒,用的是Hibernate框架,HibernateSessionFactory这个类大家会用Hibernate应该都会知道,我就不贴出了。
- package cn.yo.dao;
-
- import java.util.List;
- import org.hibernate.Session;
- import cn.yo.entity.City;
- import cn.yo.entity.Province;
- import cn.yo.entity.Town;
-
- public class ProvinceDao {
- //查询全部省
- public List<Province> findProvince(){
- Session session=HibernateSessionFactory.getSession();
- String hql="from Province";
- List<Province> province=session.createQuery(hql).list();
- if(province.size()>0){
- return province;
- }
- else{
- return null;
- }
- }
- //根据省的Id查询该省下的全部市
- public List<City> findCityById(int id){
- Session session=HibernateSessionFactory.getSession();
- String hql="from City c where c.province.id=‘"+id+"‘";
- List<City> city=session.createQuery(hql).list();
- if(city.size()>0){
- return city;
- }else{
- return null;
- }
- }
- //根据市的Id查询该市下的全部镇
- public List<Town> findTownById(int id){
- Session session=HibernateSessionFactory.getSession();
- String hql="from Town t where t.city=‘"+id+"‘";
- List<Town> town=session.createQuery(hql).list();
- if(town.size()>0){
- return town;
- }else{
- return null;
- }
- }
- }
接下来是action类
- package cn.yo.action;
-
- import java.util.List;
- import org.apache.struts2.ServletActionContext;
- import net.sf.json.JSONArray;
- import net.sf.json.JsonConfig;
- import cn.yo.dao.ProvinceDao;
- import cn.yo.entity.City;
- import cn.yo.entity.Province;
- import cn.yo.entity.Town;
-
- import com.opensymphony.xwork2.ActionSupport;
-
- public class ProvinceAction extends ActionSupport {
- private String result;//返回到客户端的数据
- //省略get,set方法
-
- //获得省
- public String findProvince()throws Exception{
- ProvinceDao d=new ProvinceDao();
- List<Province> p=d.findProvince();
- System.out.println("------");
- JsonConfig config=new JsonConfig();
- //Hibernate中关联set需要过滤,不然会引起死循环。我在这吃了很大的亏,希望大家能重视
- config.setExcludes(new String[]{"cities"});
- //转化为JSON
- JSONArray jArray = JSONArray.fromObject(p,config);
- result=jArray.toString();
- return SUCCESS;
- }
-
- //获得城市
- public String findCity()throws Exception{
- ProvinceDao d=new ProvinceDao();
- int id=Integer.parseInt(ServletActionContext.getRequest().getParameter("province_id"));
- List<City> c=d.findCityById(id);
- JsonConfig config=new JsonConfig();
- config.setExcludes(new String[]{"province","towns"});
- JSONArray jArray=JSONArray.fromObject(c, config);
- result=jArray.toString();
- return SUCCESS;
- }
- //获得镇
- public String findTown()throws Exception{
- ProvinceDao d=new ProvinceDao();
- int id=Integer.parseInt(ServletActionContext.getRequest().getParameter("city_id"));
- List<Town> t=d.findTownById(id);
- JsonConfig config=new JsonConfig();
- config.setExcludes(new String[]{"city"});
- JSONArray jArray=JSONArray.fromObject(t,config);
- result=jArray.toString();
- return SUCCESS;
- }
- }
在看struts2的配置
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
- <struts>
-
- <package name="myajax" namespace="/" extends="struts-default,json-default">
- <action name="province" class="cn.yo.action.ProvinceAction" method="findProvince">
-
- <result type="json">
-
- <param name="root">result</param>
- </result>
- </action>
- <action name="city" class="cn.yo.action.ProvinceAction" method="findCity">
-
- <result type="json">
- <param name="root">result</param>
- </result>
- </action>
- <action name="town" class="cn.yo.action.ProvinceAction" method="findTown">
-
- <result type="json">
- <param name="root">result</param>
- </result>
- </action>
- </package>
- </struts>
web.xml配置文件
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
- </filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
好了,代码全部贴出,其中hibernate中实体类的配置文件,没什么大的变化,就不贴出了,Hibernate连接数据库的的配置文件也不贴出了.
表述的可能有些不好,希望能帮初学者一点小小的忙吧.有什么建议,希望大家指出.小弟感激不尽.
版权所有,转载请注明出处.