下拉列表的三级联动

3 篇文章 0 订阅
1 篇文章 0 订阅

下拉列表的三级联动,以 市 ,区 ,域 为例

感谢https://www.cnblogs.com/lishun1005/p/4058064.html 博主的分享

MVC模式实现下拉列表的三级联动

ajax实现下拉列表的三级联动, 发现从m层查出的数据,无法以request的形式传递到客户端 . 原因是ajax传到C层的初始值可能为null ,会报异常, 所以将查处的数据通过ajax传递到客户端

市的v:

<select id="city" onchange="getRegion(this.value)" class="frm-field required">
		<option>选择城市</option>
        <c:forEach items="${requestScope.cities}" var="city">
                <option value="${city.id}">${city.city_name}</option>
        </c:forEach>
</select>

市的c:

 protected void getCity(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getContextPath();
        ArrayList<City> cities = CityDAO.getCityDAO().findAll();
        request.setAttribute("cities",cities);
    }

市的m:

public ArrayList<City> findAll() {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        ArrayList<City> citys = new ArrayList<City>();
        try {
            con = DBHelper.getDBHelper().getConnection();
            String sql = "select * from city where enable='1'";
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next())
            {
                City city = new City();
                city.setId(rs.getInt("id"));
                city.setCity_name(rs.getString("city_name"));
                city.setEnable(rs.getByte("enable"));
                citys.add(city);
            }
            return citys;
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        finally {
            DBHelper.getDBHelper().close(rs,ps,con);
        }
        return null;
    }

js获取区

<script>
    function getRegion(value) {
        $("#region option").remove();
      	$("#location option").remove();
        $.ajax({
            url:"<%=path%>/RegionServlet",
            data:{method:'getRegion', city: value},
            async:false,
            success:function (mes) {
                 var regions = mes.split("@");
                  for (var i = 0; i < regions.length; i++) {
                      $("#region").append("<option value='" + regions[i] + "'>" + regions[i] + "</option>")
                  }
             }
  })//ajax结束
  
  //获取第一次改变的域
  var region = $("#region option").attr("value");
   $.ajax({
         url:"<%=path%>/LocationServlet",
         data:{method:'getLocation',region:region},
         success:function (mes) {
             var locationStr = mes.substring(0,mes.length-1);
             var locations = locationStr.split("@");
             for(var i=0;i<locations.length;i++)
              {
                 $("#location").append("<option value="+locations[i]+">"+locations[i]+"</option>");
               }
          }
    })//ajax结束
}//方法结束
                            
</script>

区的v:

<select id="region" onchange="getLocation(this.value)" class="frm-field required">
	<option>选择区域</option>

	
 </select>

区的c:

protected void getRegion(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
	{
		String path = request.getContextPath();
		String city = request.getParameter("city");

		if (city!=null){
		Integer cityId = Integer.parseInt(city);
		ArrayList<Region>regions = RegionDAO.getRegionDAO().getRegion(cityId);
		String r = "";
		for (Region region:regions)
			{
				r = r + region.getName() + "@";
			}
		String regionStr = r.substring(0,r.length()-1);
		response.getWriter().print(regionStr);

		}
	}

区的m:

public ArrayList<Region> findAll()
	{
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		ArrayList<Region> regions = new ArrayList<Region>();
		try {
			con = DBHelper.getDBHelper().getConnection();
			String sql = "select * from region where enable='1'";
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next())
			{
				Region region  = new Region();
				region.setName(rs.getString("name"));
				region.setId(rs.getInt("id"));
				region.setEnable(rs.getByte("enable"));
				regions.add(region);
			}
			return regions;
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		finally {
			DBHelper.getDBHelper().close(rs,ps,con);
		}
		return null;
	}


	public ArrayList<Region> getRegion(Integer cityId)
	{
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		ArrayList<Region> regions = new ArrayList<Region>();
		try {
			con = DBHelper.getDBHelper().getConnection();
			String sql = "select * from region where enable='1' and cityid=?";
			ps = con.prepareStatement(sql);
			ps.setInt(1,cityId);
			rs = ps.executeQuery();
			while (rs.next())
			{
				Region region  = new Region();
				region.setName(rs.getString("name"));
				region.setId(rs.getInt("id"));
				region.setEnable(rs.getByte("enable"));
				regions.add(region);
			}
			return regions;
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		finally {
			DBHelper.getDBHelper().close(rs,ps,con);
		}
		return null;
	}

域的v:

<select id="location" class="frm-field required">
							<option>选择位置</option>
							
						 </select>

域的js

<script type="text/javascript">
		function getLocation(value) {
		$("#location option").remove();
		$.ajax({
			url: "<%=path%>/LocationServlet",
			data: {method: 'getLocation', region: value},
			success:function (mes) {
			var locationStr = mes.substring(0,mes.length-1);
			var locations = locationStr.split("@");
				for(var i=0;i<locations.length;i++)
				 {
					 $("#location").append("<option value="+locations[i]+">"+locations[i]+"</option>");
				 }

			 }
	 })//ajax结束
 }
	</script>

域的c:

 protected void getLocation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getContextPath();
        try {
            String regionStr = request.getParameter("region");
            Integer regionId = 0;
            ArrayList<Region> regions = RegionDAO.getRegionDAO().findAll();
            for (Region region:regions
                 ) {
                    if (regionStr.equals(region.getName()))
                    {
                        regionId = region.getId();
                    }
            }
            ArrayList<Location> locations =  LocationDAO.getLocationDAO().getLocation(regionId);
            PrintWriter out = response.getWriter();
            String locationStr = "";
            for (Location location:locations
                 ) {
                locationStr = locationStr + location.getLocation_name() + "@";
            }
            out.print(locationStr);

        } catch (NumberFormatException e) {
            //e.printStackTrace();
        }


    }

域的m:

 public ArrayList<Location> getLocation(Integer region)
    {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        ArrayList<Location> locations = new ArrayList<Location>();
        try {
            con = DBHelper.getDBHelper().getConnection();
            String sql = "select * FROM location WHERE region_id=? and enable='1'";
            ps = con.prepareStatement(sql);
            ps.setInt(1,region);
            rs = ps.executeQuery();
            while (rs.next())
            {
                Location location = new Location();
                location.setId(rs.getInt(1));
                location.setLocation_name(rs.getString("location_name"));
                location.setRegion_id(rs.getInt(3));
                location.setInitial(rs.getString("initial"));
                locations.add(location);
            }
            return locations;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBHelper.getDBHelper().close(rs,ps,con);
        }
        return null;
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值