jquery +ajax +json实现动态级联加载
<!-- 导入jquey库文件 --><script type="text/javascript" src="js/jquery-1.3.1.js"></script><script type="text/javascript">//使用Ajax结合Jquery+后台Json 实现联动菜单//使用Jquery进行Ajax代码的简化function showCity(province){//4个参数类型分别为:提交路径,传递的参数,回调函数,返回数据类型$.post("<%=basePath%>pages/user!showCity.action",{"user.province":province},showCityCallback,"json");}//回调函数,Jquery会自动将结果转换为对象,并传递到回调函数中。function showCityCallback(obj){//按Id查询页面元素var city=$("#city");//设置属性,每次改变时清空在显示city.attr("length",1);for(var i=0;i<obj.allCity.length;i++){var cid=obj.allCity[i].cid;var cname=obj.allCity[i].cname;//添加子节点var option="<option value='"+cid+"'>"+cname+"</option>";city.append(option);}}</script>
?
<select id="province" name="user.province" onchange="showCity(this.value);"><option value="0">-请选择省份-</option> <c:if test="${allProvince!=null}"> <c:forEach var="province" items="${allProvince}"> <c:if test="${user.province==province.pid}"><option value="${province.pid}" selected="selected">${province.pname}</option></c:if><c:if test="${user.province!=province.pid}"><option value="${province.pid}" >${province.pname}</option></c:if></c:forEach></c:if></select><select id="city" name="user.city"><option value="${user.city}">-请选择城市-</option></select>?
public String showCity()throws Exception{List<City> allCity=provinceService.findCityByPid(user.getProvince());//使用org.Json来拼写字符串JSONObject root=new JSONObject(); //定义JSONArray array=new JSONArray();//迭代循环将每个对象obj放入数组arrayIterator<City> iter=allCity.iterator();while (iter.hasNext()) {City city=iter.next();JSONObject obj=new JSONObject();obj.put("cid", city.getCid());obj.put("cname", city.getCname());array.put(obj);}//将array数组放入节点root对象中返回给Ajax调用root.put("allCity", array);HttpServletResponse response=ServletActionContext.getResponse(); //取得response对象response.setCharacterEncoding("GBK");response.setContentType("text/html");PrintWriter out=response.getWriter();out.print(root.toString());out.close();return null;}?