默认查出一级分类的第一条数据,和一级分类第一条对应的二级分类条目,当选择一级分类的其他条目时,通过ajax查询出数据库中对应的二级分类条目,返回json格式的数据,并显示在二级分类的下拉列表中。
编程实现:
前端页面jsp:
class="Html" name="code">
产品分类
| ${data.name} ${data.name} |
jsp中的ajax的js部分:
javascript" name="code">
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
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 clist = (List) 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;
}