servlet+json+ajax集成
模拟下拉列表二级菜单联动
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();
}
}