spring注解@ResponseBody处理ajax请求,json数据类型

json需要引用的JSON包有:jackson-core-asl-1.9.13.jar,jackson-mapper-asl-1.9.13.jar,版本并不是固定的,只是这两个的版本一样就行了
controller层:

@RequestMapping(value = "branchMap")
 @ResponseBody
 public List getBranchMap(HttpServletRequest request) {
  String tmp = request.getParameter("organizid");
  Long id = Long.parseLong(tmp);
  return serviceManager.getBranchMap(id);
 }

service层:

public List getBranchMap(Long id) {
  return institutionsDao.getBranchMap(id);
 }

dao层:(其中Temp是临时类,就是institutions类想要的字段组成的类)

public List getBranchMap(Long id) {
  List lt = new ArrayList();
  String sql = "select s.id,s.name from institutions s where s.parent=?";
  Session session = this.getSession();
  SQLQuery sqlQuery = session.createSQLQuery(sql);
  sqlQuery.setLong(0, id);
  sqlQuery.addScalar("id", Hibernate.LONG);
  sqlQuery.addScalar("name", Hibernate.STRING);
  sqlQuery.setResultTransformer(Transformers
    .aliasToBean(Institutions.class));
  List list = sqlQuery.list();
  if (list.size() <= 0) {
   Temp t = new Temp();
   t.setId(0L);
   if (id == -1) {
    t.setName("请先选择机构");
   } else {
    t.setName("该机构没有分支");
   }
   lt.add(t);
   return lt;
  }
  for (int i = 0; i < list.size(); i++) {
   Institutions ins = list.get(i);
   Temp t = new Temp();
   t.setId(ins.getId());
   t.setName(ins.getName());
   lt.add(t);
  }
  return lt;
 }

jsp层:

  var val=$("#organization option:selected").val();
       $.ajax({
           type:"post",
           [url:"${ctx}/account/user/branchMap](https://blog.csdn.net/dcx903170332/article/details/17957579/' rel=)",
           dataType:"json",
           async:false,
           data:{organizid:val},
           success:function(data){
            $("#branch").html("");
               $.each(data,function(i,item){
                   $("#branch").append("");
               });
           }
       });

然后在对应的spring-mvc.servlet.xml中添加配置

 
  
   
    
     
      
       
       application/json;charset=UTF-8
      
     
    
   
  
 

只要后台查询查询的结果集是list泛型的list集合然后把controller层标注上 @ResponseBody,前台调用此方法,并在$.ajax中标示为dataType:"json", async:false,即可。

你可能感兴趣的:(spring注解@ResponseBody处理ajax请求,json数据类型)