Ajax實現省市無窮級聯動

來源:互聯網
上載者:User

這是一個Servlet應用。。

這裡用到了Json-lib工具包,關於Json-lib的使用,請參見我的博文

http://blog.csdn.net/jadyer/archive/2011/02/01/6171659.aspx

首先是web.xml檔案

<?xml version="1.0" encoding="UTF-8"?><br /><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"<br />xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br />xsi:schemaLocation="http://java.sun.com/xml/ns/javaee<br />http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><br /><servlet><br /><servlet-name>InitProvinceServlet</servlet-name><br /><servlet-class>com.jadyer.servlet.InitProvinceServlet</servlet-class><br /></servlet><br /><servlet><br /><servlet-name>GetCityServlet</servlet-name><br /><servlet-class>com.jadyer.servlet.GetCityServlet</servlet-class><br /></servlet><br /><servlet><br /><servlet-name>GetAreaServlet</servlet-name><br /><servlet-class>com.jadyer.servlet.GetAreaServlet</servlet-class><br /></servlet></p><p><servlet-mapping><br /><servlet-name>InitProvinceServlet</servlet-name><br /><url-pattern>/servlet/InitProvinceServlet</url-pattern><br /></servlet-mapping><br /><servlet-mapping><br /><servlet-name>GetCityServlet</servlet-name><br /><url-pattern>/servlet/GetCityServlet</url-pattern><br /></servlet-mapping><br /><servlet-mapping><br /><servlet-name>GetAreaServlet</servlet-name><br /><url-pattern>/servlet/GetAreaServlet</url-pattern><br /></servlet-mapping></p><p><!-- 在version="2.5"中,可以直接在<welcome-file-list>裡執行Servlet應用 --><br /><welcome-file-list><br /><welcome-file>servlet/InitProvinceServlet</welcome-file><br /></welcome-file-list><br /></web-app>

然後是用來顯示省市無窮級聯動效果的index.jsp頁面

<%@ page language="java" pageEncoding="UTF-8"%><br /><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%></p><p><script type="text/javascript"><br />var xmlHTTP = new XMLHttpRequest(); //支援Internet Explorer-8.0.6001.18702</p><p>var theTagID; //定義的全域變數,以便於在回呼函數中使用之<br />function getCityList(provinceID, tagID){<br />var isDelete = false;<br />theTagID = tagID;<br />var sons = document.getElementById(tagID).childNodes;<br />for(var i=(sons.length-1); i>=0; i--){<br />if("A" != sons[i].nodeName.toUpperCase()){<br />//if("UL" == sons[i].nodeName.toUpperCase()){ //二者等效<br />sons[i].parentNode.removeChild(sons[i]);<br />isDelete = true;<br />}<br />}<br />if(isDelete){<br />return;<br />}<br />xmlHTTP.open('GET', '${pageContext.request.contextPath}/servlet/GetCityServlet?provinceID='+provinceID, true);<br />xmlHTTP.onreadystatechange = callbackCityList;<br />xmlHTTP.setRequestHeader("if-Modified-Since", "0");<br />xmlHTTP.send(null);<br />return false;<br />}</p><p>function callbackCityList(){<br />if(4==xmlHTTP.readyState && 200==xmlHTTP.status){<br />var citys = eval(xmlHTTP.responseText);<br />if(0 == citys.length){<br />return;<br />}<br />var parentLI = document.getElementById(theTagID);<br />var newUL = document.createElement("ul");</p><p>for(var i=0; i<citys.length; i++){<br />var newLI = document.createElement("li");<br />newLI.id = "tag" + citys[i].cityID;<br />newLI.innerHTML = "<a href='#' onclick='getCityList(" + citys[i].cityID + ", /"tag" + citys[i].cityID + "/");'>" + citys[i].cityName + "</a>";<br />newUL.appendChild(newLI);<br />}<br />parentLI.appendChild(newUL);<br />}<br />}<br /></script></p><p><ul><br /><c:forEach items="${requestScope.provinces}" var="province"><br /><li id="tag${province.cityID}"><a href="#" onclick="return getCityList(${province.cityID}, 'tag${province.cityID}');">${province.cityName}</a></li><br /></c:forEach><br /></ul>

然後是用於從資料庫執行查詢操作的CityDao.java

package com.jadyer.dao;</p><p>import java.sql.Connection;<br />import java.sql.PreparedStatement;<br />import java.sql.ResultSet;<br />import java.sql.SQLException;<br />import java.util.ArrayList;<br />import java.util.List;</p><p>import javax.naming.Context;<br />import javax.naming.InitialContext;<br />import javax.naming.NamingException;<br />import javax.sql.DataSource;</p><p>import com.jadyer.model.City;</p><p>/**<br /> * 這裡的代碼,應該重構一下,但為了示範方便,就沒有重構<br /> */<br />public class CityDao {<br />/**<br /> * 根據父ID得到所有一級子類<br /> * @see 如果傳遞為0,則得到所有根節點<br /> */<br />public List<City> findByParentID(int parentID){<br />String sql = "select cityID, cityName from city where parentID=?";<br />List<City> citys = new ArrayList<City>();<br />try {<br />Context context = new InitialContext();<br />//有關jdbc/oracleds串連池的配置,參見http://blog.csdn.net/jadyer/archive/2010/11/10/6001023.aspx<br />DataSource ds = (DataSource)context.lookup("java:/comp/env/jdbc/oracleds");<br />Connection conn = ds.getConnection();<br />PreparedStatement pstmt = conn.prepareStatement(sql);<br />pstmt.setInt(1, parentID);<br />ResultSet rs = pstmt.executeQuery();<br />while(rs.next()){<br />citys.add(new City(rs.getInt("cityID"), rs.getString("cityName")));<br />}<br />} catch (NamingException e) {<br />e.printStackTrace();<br />} catch (SQLException e) {<br />e.printStackTrace();<br />}<br />return citys;<br />}</p><p>/**<br /> * 根據ID得到該城市的詳細資料<br /> */<br />public City fingByCityID(int cityID){<br />String sql = "select cityName from city where cityID=?";<br />City city = null;<br />try {<br />Context context = new InitialContext();<br />DataSource ds = (DataSource)context.lookup("java:/comp/env/jdbc/oracleds");<br />Connection conn = ds.getConnection();<br />PreparedStatement pstmt = conn.prepareStatement(sql);<br />pstmt.setInt(1, cityID);<br />ResultSet rs = pstmt.executeQuery();<br />while(rs.next()){<br />city = new City(cityID, rs.getString("cityName"));<br />}<br />} catch (NamingException e) {<br />e.printStackTrace();<br />} catch (SQLException e) {<br />e.printStackTrace();<br />}<br />return city;<br />}<br />}

用於儲存City資訊的實體類

package com.jadyer.model;</p><p>import java.util.List;</p><p>public class City {<br />private Integer parentID;<br />private Integer cityID;<br />private String cityName;<br />private List<City> areas; //用於儲存該城市下所有區縣的詳細資料</p><p>/* 四個屬性的getter和setter方法略 */</p><p>public City(){}</p><p>public City(Integer cityID, String cityName){<br />this.cityID = cityID;<br />this.cityName = cityName;<br />}<br />}

用於初始化所有省份資訊的InitProvinceServlet.java

package com.jadyer.servlet;</p><p>import java.io.IOException;</p><p>import javax.servlet.ServletException;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;</p><p>import com.jadyer.dao.CityDao;</p><p>@SuppressWarnings("serial")<br />public class InitProvinceServlet extends HttpServlet {<br />public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {<br />CityDao cityDao = new CityDao();<br />//擷取所有省份的資訊<br />request.setAttribute("provinces", cityDao.findByParentID(0));<br />request.getRequestDispatcher("/index.jsp").forward(request, response);<br />}<br />}

用於擷取指定省份下的所有城市資訊的GetCityServlet.java

package com.jadyer.servlet;</p><p>import java.io.IOException;<br />import java.util.List;</p><p>import javax.servlet.ServletException;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;</p><p>import net.sf.json.JSONArray;</p><p>import com.jadyer.dao.CityDao;<br />import com.jadyer.model.City;</p><p>@SuppressWarnings("serial")<br />public class GetCityServlet extends HttpServlet {<br />public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {<br />response.setContentType("text/html; charset=UTF-8");<br />int provinceID = Integer.parseInt(request.getParameter("provinceID"));<br />CityDao cityDao = new CityDao();<br />//返回該省份下的所有城市的資訊<br />List<City> citys = cityDao.findByParentID(provinceID);<br />JSONArray jsonObject = JSONArray.fromObject(citys);<br />response.getWriter().println(jsonObject.toString());<br />}<br />}

用於擷取指定城市下的所有區縣資訊的GetAreaServlet.java

package com.jadyer.servlet;</p><p>import java.io.IOException;<br />import java.util.List;</p><p>import javax.servlet.ServletException;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;</p><p>import net.sf.json.JSONObject;</p><p>import com.jadyer.dao.CityDao;<br />import com.jadyer.model.City;</p><p>@SuppressWarnings("serial")<br />public class GetAreaServlet extends HttpServlet {<br />public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {<br />response.setContentType("text/html; charset=UTF-8");<br />int cityID = Integer.parseInt(request.getParameter("cityID"));<br />CityDao cityDao = new CityDao();<br />//得到該城市下所有區縣的詳細資料的集合<br />List<City> areas = cityDao.findByParentID(cityID);<br />//得到當前城市的詳細資料<br />City city22 = cityDao.fingByCityID(cityID);<br />city22.setAreas(areas);<br />JSONObject jsonObject = JSONObject.fromObject(city22);<br />response.getWriter().println(jsonObject.toString());<br />}<br />}

最後是資料庫指令碼檔案

--Oracle 11g<br />--建立表格<br />create table city(<br />id number(3) primary key,<br />parentID number(3), --0表示根節點<br />cityID number(3),<br />cityName varchar(20)<br />)</p><p>--建立序列<br />create sequence city_sequence increment by 1 start with 1 nomaxvalue nocycle;</p><p>--添加一級菜單<br />insert into city values(city_sequence.nextval, 0, 1, '黑龍江');<br />insert into city values(city_sequence.nextval, 0, 2, '吉林省');<br />insert into city values(city_sequence.nextval, 0, 3, '遼寧省');<br />--添加二級菜單<br />insert into city values(city_sequence.nextval, 1, 4, '哈爾濱');<br />insert into city values(city_sequence.nextval, 1, 5, '佳木斯');<br />insert into city values(city_sequence.nextval, 1, 6, '雙鴨山');<br />insert into city values(city_sequence.nextval, 2, 7, '長春');<br />insert into city values(city_sequence.nextval, 2, 8, '遼源');<br />insert into city values(city_sequence.nextval, 2, 9, '通化');<br />insert into city values(city_sequence.nextval, 3, 10, '瀋陽');<br />insert into city values(city_sequence.nextval, 3, 11, '大連');<br />insert into city values(city_sequence.nextval, 3, 12, '鐵嶺');<br />--添加三級菜單<br />--這裡只提供了黑龍江省的三級聯動資料,關於其它省份的資料,請自行添加<br />insert into city values(city_sequence.nextval, 4, 13, '巴彥縣');<br />insert into city values(city_sequence.nextval, 4, 14, '延壽縣');<br />insert into city values(city_sequence.nextval, 4, 15, '木蘭縣');<br />insert into city values(city_sequence.nextval, 5, 16, '撫遠縣');<br />insert into city values(city_sequence.nextval, 5, 17, '湯原縣');<br />insert into city values(city_sequence.nextval, 5, 18, '樺川縣');<br />insert into city values(city_sequence.nextval, 6, 19, '集賢縣');<br />insert into city values(city_sequence.nextval, 6, 20, '寶清縣');<br />insert into city values(city_sequence.nextval, 6, 21, '友誼縣');<br />--添加四級菜單<br />--這裡只提供了哈爾濱市的四級聯動資料,其它資料,請自行添加<br />insert into city values(city_sequence.nextval, 13, 22, '興隆鎮');<br />insert into city values(city_sequence.nextval, 13, 23, '龍廟鎮');<br />insert into city values(city_sequence.nextval, 13, 24, '窪興鎮');<br />insert into city values(city_sequence.nextval, 14, 25, '六團鎮');<br />insert into city values(city_sequence.nextval, 14, 26, '中和鎮');<br />insert into city values(city_sequence.nextval, 14, 27, '加信鎮');<br />insert into city values(city_sequence.nextval, 15, 28, '東興鎮');<br />insert into city values(city_sequence.nextval, 15, 29, '大貴鎮');<br />insert into city values(city_sequence.nextval, 15, 30, '新民鎮');<br />--添加五級菜單<br />--這裡只提供了巴彥縣的五級聯動資料,其它資料,請自行添加<br />insert into city values(city_sequence.nextval, 22, 31, '長春鄉');<br />insert into city values(city_sequence.nextval, 22, 32, '豐樂鄉');<br />insert into city values(city_sequence.nextval, 22, 33, '德祥鄉');<br />insert into city values(city_sequence.nextval, 23, 34, '山後鄉');<br />insert into city values(city_sequence.nextval, 23, 35, '華山鄉');<br />insert into city values(city_sequence.nextval, 23, 36, '紅光鄉');<br />insert into city values(city_sequence.nextval, 24, 36, '鎮東鄉');<br />insert into city values(city_sequence.nextval, 24, 36, '富江鄉');<br />insert into city values(city_sequence.nextval, 24, 36, '松花鄉');<br />--添加六級菜單<br />--理論上可無限添加。但實際中,用到四級菜單的情況都不是太多,故以下資料略

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.