Struts2处理得到要数据并将数据转换为JSON格式
public String execute() throws Exception { // TODO Auto-generated method stub ICategoryDAO categoryDAO = new CategoryDAO(); //得到所有数据 List<Categories> categoriesList = categoryDAO.getCategories(); Map<Integer, Categories> map = new HashMap<Integer, Categories>(); //循环数据讲数据装入Map集合中 for (Categories category : categoriesList) { Categories categories = new Categories(); categories.setCategoryId(category.getCategoryId()); categories.setCategoryName(category.getCategoryName()); map.put(category.getCategoryId(), categories); } //返回 json JSONObject jsonObject = new JSONObject(); //将Map格式化成JSON格式 result = jsonObject.fromObject(map).toString(); return SUCCESS; }
JSP页面将返回的JSON数据解析为JSON对象,并遍历出来
$(document).ready(function(){ //1、异步加载Categories 电影类别 $.ajax({ url:"GetCategories.action", type:"post", dataType:"json", success:function(data){ //得到返回的 Categories参数 ,并解析成JSON对象 var result = JSON.parse(data.result); //IE8.0 FF3.0 //生成option,添加到 select节点中 $.each(result,function(i){ $("<option value=" + result[i].categoryId + ">" + result[i].categoryName + "</option>").appendTo("#categories"); }); } }); });
本文详细介绍了如何使用Struts2框架处理数据,并将其转换为JSON格式。通过实例展示了从数据库获取数据,封装成Map集合,然后转换为JSON的过程。最后,通过AJAX异步请求获取JSON数据,并在JSP页面中解析和展示。
2463

被折叠的 条评论
为什么被折叠?



