Jquery的强大不用赘语了,今天就分享一下用jquery来调用servelt集合数据,然后填充到下拉框中:
下面是servlet:/LoadPrdClassServlet中的doPost方法,集合数据转换成JSON数据格式
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
response.setContentType("text/html;charset=UTF-8");
prdClassService = new PrdClassService();
List<PrdClass> prdList = prdClassService.getPrdList();
StringBuffer strBuff = new StringBuffer("{\"PrdClass\":[");
for (PrdClass prdClass : prdList) {
strBuff.append("{\"prdClass\":\"").append(prdClass.getPrdClass()).append("\",\"prdName\":\"")
.append(prdClass.getPrdName()).append("\"},");
}
strBuff.deleteCharAt(strBuff.lastIndexOf(","));
strBuff.append("]}");
//System.out.println("strBuff字符串"+strBuff.toString());
response.getWriter().print(strBuff.toString());
}
<script type="text/javascript">
<!--
$(document).ready(function(){//填充产品大类目前优化
$.getJSON("/LoadPrdClassServlet",function(data){
var str = "<option value=''>请选择</option>"
$.each(data.PrdClass,function(i,items) {
var tmp = "<option value="+items.prdClass+">"+items.prdName+"</option>";
str = str+tmp;
});
$("#searchPrd").html(str)
});
});
//-->
</script>