系统开发中,经常遇到级联Select的状况,而级联的Select Option数据一般记录于DB,如果每次都重新写一套级联Select,工作将是繁琐滴。。。

一般来说,写一套级联的Select的几个步骤:

  1. 从DB读取Select Option的级联数据
  2. 将数据封装成JSON或xml传到前台
  3. 在前台由JS动态组装/填充Select元素
  4. 用JS调整各个级联Select之间的交互,如父Select值发生改变,重新填充子Select的选项,并清空子Select的已选值

  而这次,想写一套可重用的代码,便于以后有需要的时候可方便的搬进以后的项目,本代码依赖于

  1. Gson 2.2.4
  2. Jquery 1.6.1

  

  Kick-off:

  首先,由于是Demo,我们不从DB查询数据,只是用Collection直接模拟数据,为了便于生成JSON,使用Gson转换,为了组装级联数据结构方便,使用Selector.java和SelectorOption.java作为存储的结构:

 import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; public class CascapeSelectorServlet extends HttpServlet {
private static final long serialVersionUID = 1L; public CascapeSelectorServlet() {
super();
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* country */
Selector countrySelector = new Selector("country", null, getCountry()); /* province */
Selector provinceSelector = new Selector("province", null, new HashMap());
List<SelectorOption> provinceList = getProvince();
for (int i = 0; i < provinceList.size(); i++) {
provinceSelector.put(provinceList.get(i).getParent(), provinceList.get(i));
} /* city */
Selector citySelector = new Selector("city", null, new HashMap());
List<SelectorOption> cityList = getCity();
for (int i = 0; i < cityList.size(); i++) {
citySelector.put(cityList.get(i).getParent(), cityList.get(i));
} Map dataMap = new HashMap();
dataMap.put("country", countrySelector);
dataMap.put("province", provinceSelector);
dataMap.put("city", citySelector); /* Gson */
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
Gson gson = gsonBuilder.create(); /* To json */
String json = gson.toJson(dataMap); System.out.println("json -> " + json);
response.getWriter().write(json);
} /**
* Analog data
* @return
*/
private List<SelectorOption> getCountry() {
List countryList = new ArrayList();
countryList.add(new SelectorOption("cn", "China"));
countryList.add(new SelectorOption("uk", "United Kingdom"));
countryList.add(new SelectorOption("ca", "Canada"));
countryList.add(new SelectorOption("us", "United States")); return countryList;
} /**
* Analog data
* @return
*/
private List<SelectorOption> getProvince() {
List provinceList = new ArrayList();
provinceList.add(new SelectorOption("hb", "Heibei", "cn"));
provinceList.add(new SelectorOption("zj", "Zhejiang", "cn"));
provinceList.add(new SelectorOption("gd", "Guangdong", "cn"));
provinceList.add(new SelectorOption("gx", "Guangxi", "cn"));
provinceList.add(new SelectorOption("ca", "California", "us")); return provinceList;
} /**
* Analog data
* @return
*/
private List<SelectorOption> getCity() {
List cityList = new ArrayList();
cityList.add(new SelectorOption("gz", "Guangzhou", "gd"));
cityList.add(new SelectorOption("nn", "Nanning", "gx"));
cityList.add(new SelectorOption("fs", "Foshan", "gd"));
cityList.add(new SelectorOption("hz", "Huizhou", "gd"));
cityList.add(new SelectorOption("la", "Los Angeles", "ca")); return cityList;
} }

CascapeSelectorServlet.java

  SelectorOption.java用于装一个Select的Option数据:

 public class SelectorOption {

     private String value;
private String name;
private String parent; public String getValue() {
return value;
} public void setValue(String value) {
this.value = value;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getParent() {
return parent;
} public void setParent(String parent) {
this.parent = parent;
} public SelectorOption(String value, String name) {
super();
this.value = value;
this.name = name;
} public SelectorOption(String value, String name, String parent) {
super();
this.value = value;
this.name = name;
this.parent = parent;
} }

SelectorOption.java

  Selector.java用于装一个Selecti的数据:

 import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public class Selector { private String name;
private String parent;
private Map dataMap; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getParent() {
return parent;
} public void setParent(String parent) {
this.parent = parent;
} public Map getDataMap() {
return dataMap;
} public void setDataMap(Map dataMap) {
this.dataMap = dataMap;
} public Selector(String name, String parent, List dataList) {
super();
this.name = name;
this.parent = parent;
this.dataMap = new HashMap();
this.dataMap.put("default", dataList);
} public Selector(String name, String parent, Map dataMap) {
super();
this.name = name;
this.parent = parent;
this.dataMap = dataMap;
} public void put(String key, Object object) { if (key == null || key.length() == 0) {
return;
} if (object == null) {
return;
} if (this.dataMap == null) {
this.dataMap = new HashMap();
} if (this.dataMap.containsKey(key) && this.dataMap.get(key) != null) {
List tempList = (List)this.dataMap.get(key);
tempList.add(object);
} if (!this.dataMap.containsKey(key)) {
List tempList = new ArrayList();
tempList.add(object); this.dataMap.put(key, tempList);
} } }

Selector.java

  cascsel.js则用于处理各个级联Select之间的交互:

 /**
* Register & initialize select
*/
function registerSelector(data, array, index) {
if (!array || array.length == 0) {
return;
} if (index < 0 || index >= array.length) {
return;
} if (!data[array[index]]) {
return;
} var $select = $("[name='" + array[index] + "']"); /* Initialize default select */
var dataList = data[array[index]]["dataMap"]["default"];
if (dataList && dataList.length > 0) {
$select.empty();
for (var i = 0; i < dataList.length; i++) {
$select.append("<option value='" + dataList[i]["value"] + "'>" + dataList[i]["name"] + "</option>")
}
} /* Register onchange event for select */
if ((index + 1) < array.length && data[array[index + 1]]) {
$select.bind("change", function(event) {
var value = $select.val();
var dataList = data[array[index + 1]]["dataMap"][value]; $nextSelect = $("[name='" + array[index + 1] + "']");
/* If the option of select changes, refactor the cascape select */
if (dataList && dataList.length > 0) {
$nextSelect.empty();
for (var i = 0; i < dataList.length; i++) {
$nextSelect.append("<option value='" + dataList[i]["value"] + "'>" + dataList[i]["name"] + "</option>")
}
} else {
$nextSelect.empty();
} /* Trigger */
$nextSelect.trigger("change");
}); $select.trigger("change");
} registerSelector(data, array, index + 1); }

cascsel.js

  cascsel.jsp为Demo的展示页面(调用cascsel.js):

 <%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!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">
<script type="text/javascript" src="js/jquery-1.6.1.js"></script>
<script type="text/javascript" src="js/cascsel.js"></script>
<script type="text/javascript">
$().ready(function() { querySelector(); }); /**
* Get select json by ajax
*/
function querySelector() {
$.ajax({
url : "CascapeSelectorServlet",
dataType : "json",
type : "post",
contentType : "application/x-www-form-urlencoded; charset=utf-8",
cache : false,
error : function(dty, errorType) {
alert(errorType);
},
success : function(data) {
registerSelector(data, ["country", "province", "city"], 0);
}
});
} </script> <title>Cascape Select</title>
</head>
<body> <select name="country" ></select>
<select name="province" ></select>
<select name="city" ></select> </body>
</html>

cascsel.jsp

Enjoy it!

05-13 11:56