jQuery ajax级联二级菜单(转)
默认查出一级分类的第一条数据,和一级分类第一条对应的二级分类条目,当选择一级分类的其他条目时,通过ajax查询出数据库中对应的二级分类条目,返回json格式的数据,并显示在二级分类的下拉列表中。
编程实现:
前端页面jsp:
<form method="post" modelAttribute="_pro" name="form1" id="form1" action="${ctx}/product-manage/add-product"> <table width="100%" border="1" align="center" cellpadding="6" cellspacing="0" bordercolor="#FFFFFF" bgcolor="#F7F7F7"> <tr> <td width="15%" bgcolor="#F7F7F7"><div align="center">产品分类</div></td> <td bgcolor="#F7F7F7"> <select name="pid" id="pid" onchange="getData()"> <c:forEach var="data" items="${clist}"> <option value="${data.id}">${data.name}</option> </c:forEach> </select> <select name="categoryId" id="categoryId"> <c:forEach var="data" items="${slist}"> <option value="${data.id}">${data.name}</option> </c:forEach> </select> </td> </tr> </form>
jsp中的ajax的js部分:
<script src="${ctx}/js/jquery-1.7.1.min.js"></script> function getData() { var pid = $("#pid").val(); $.ajax({ url:"${ctx}/product-manage/sub-category?"+Math.random(), data:{pid : pid}, type : "post", cache : false, dataType : "json", error:function(){ alert("error occured!!!"); }, success:function(data){ if(data!="0"){ var categoryId = document.getElementById('categoryId'); //清空数组 categoryId.length = 0; for(var i=0;i<data.length;i++){ var xValue=data[i].id; var xText=data[i].name; var option=new Option(xText,xValue); categoryId.add(option); } }else{ var categoryId = document.getElementById('categoryId'); categoryId.length = 0; } } }); }
后端的json处理代码:
/** * 得到产品种类对应的子种类 : json数据 * @throws IOException */ @SuppressWarnings("unchecked") @RequestMapping(value="sub-category") public String getSubCategory(HttpServletRequest request, HttpServletResponse response) throws IOException{ response.setContentType("text/xml;charset=UTF-8"); PrintWriter out = null; try { out = response.getWriter(); } catch (IOException e) { e.printStackTrace(); } String pid = request.getParameter("pid"); String sql = "select id,name from product_category where pid=?"; List<ProductCategory> clist = (List<ProductCategory>) DBHandler.queryBeanList(sql, ProductCategory.class, pid); JSONArray array = new JSONArray(); JSONObject member = null; try { for (ProductCategory p:clist) { member = new JSONObject(); member.put("name", p.getName()); member.put("id", p.getId()); array.put(member); } } catch (JSONException e) { e.printStackTrace(); } out.print(array.toString()); return null; }
相关推荐
TONIYH 2020-07-22
83510998 2020-07-18
wcqwcq 2020-06-26
delmarks 2020-06-14
ppsurcao 2020-06-14
tthappyer 2020-06-07
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03