json需要引用的JSON包有:jackson-core-asl-1.9.13.jar,jackson-mapper-asl-1.9.13.jar,版本并不是固定的,只是这两个的版本一样就行了
controller层:
@RequestMapping(value = "branchMap")
@ResponseBody
public List<Temp> getBranchMap(HttpServletRequest request) {
String tmp = request.getParameter("organizid");
Long id = Long.parseLong(tmp);
return serviceManager.getBranchMap(id);
}
service层:
public List<Temp> getBranchMap(Long id) {
return institutionsDao.getBranchMap(id);
}
dao层:(其中Temp是临时类,就是institutions类想要的字段组成的类)
public List<Temp> getBranchMap(Long id) {
List<Temp> lt = new ArrayList<Temp>();
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<Institutions> 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("<option value="+item.id+">"+item.name+"</option>");
});
}
});
然后在对应的spring-mvc.servlet.xml中添加配置
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<!--返回字符串格式json-->
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
只要后台查询查询的结果集是list<XXX>泛型的list集合然后把controller层标注上 @ResponseBody,前台调用此方法,并在$.ajax中标示为dataType:"json", async:false,即可。