類比下拉式清單二級菜單聯動
1、頁面
<tr>
<td align="right"><font color="red">*</font>一級服務類型:</td>
<td>
<select name="dept" id="dept" onchange="loadDeptChild(this.options[this.options.selectedIndex].value)"/>
<option value="0">請選擇...</option>
<c:forEach items="${depts}" var="dept">
<option value ="${dept.id }">${dept.name }</option>
</c:forEach>
</select>
<span style="color:red">${errDept}</span>
</td>
</tr>
<tr>
<td align="right">二級服務類型:</td>
<td>
<select name="deptChild" id="deptChild">
<option value="0">請選擇...</option>
</select>
</td>
</tr>
2、js
function loadDeptChild(dept){
var url="servlet/CustomerServlet?action=loadDeptChild&dept="+dept;
$.get(url, null, function(data){
var objs=eval("("+data+")"); //解析json對象
var deptChild=$("#deptChild");
deptChild.empty(); //初始化否則會追加
deptChild.append("<option value='0'>請選擇...</option>");
for(var i=0;i<objs.length;i++){
deptChild.append("<option value='"+objs[i].id+"'>"+objs[i].name+"</option>");
}
});
}
3、servlet
/**
* 實現服務類型select二級聯動
*
* @throws ServletException
* @throws IOException
*/
public void loadDeptChild() throws ServletException, IOException {
// 設定頁面utf-8編碼
// response.setContentType("text/html;charset=utf-8");
// 可以自動識別為Json對象,否則eval解析json無效
response.setContentType("application/x-javascript;charset=UTF-8");
PrintWriter out = response.getWriter();
Integer dept = Integer.parseInt(request.getParameter("dept"));
List<Dictionary> models = customerDao.getDeptChilds(dept);
if (models != null && models.size() > 0) {
//構造json對象
StringBuffer json = new StringBuffer();
json.append("[");
for (Dictionary model : models) {
json.append('{');
json.append("id:").append(model.getId()).append(",");
json.append("name:").append("'").append(model.getName().trim()).append("'");
json.append("},");
}
json.deleteCharAt(json.length() - 1);
json.append("]");
out.println(json.toString());
out.close();
} else {
out.println("[{id:0,name:''}]");
out.close();
}
}