1)、在Controller中写
//@ResponseBody响应体是jackson包提供的
用于将Controller的方法返回的对象,通过HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端
写在上方
@ResponseBody @RequestMapping("/getallajax") public Collection<Employee> ajaxGetAll(){ Collection<Employee> all = employeeDao.getAll(); return all; }
返回数据all就是json就ok;
2)、在页面中写,$.ajax();
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <% pageContext.setAttribute("ctp", request.getContextPath()); %> <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script> </head> <body> <!--%=new Date() %验证默认行为已被禁止--> <%=new Date() %> <a href="${ctp }/getallajax">ajax获取所有员工</a><br/> <div> </div> <!--return false;禁用默认行为--> <script type="text/javascript"> $("a:first").click(function(){ //1、发送ajax获取所有员工上 $.ajax({ url:"${ctp}/getallajax", type:"GET", success:function(data){ //console.log(data); $.each(data,function(){ var empInfo = this.lastName+"-->"+this.birth+"--->"+this.gender; $("div").append(empInfo+"<br/>"); }); } }); return false; }); </script> </body> </html>