列1:通过id查询显示数据
$(".viewUser").click(function () { var id=$(this).attr("userid"); alert(id) $.ajax({ type:"get", //这里用到了restful风格 url:"/jsp/view/"+id, //返回一个json对象 dataType:"json", success:function (result) { //这里的result是User对象,传过来一个对象,通过id拿到jsp页面,传入值 $("#userCode").html(result.userCode) $("#userName").html(result.userName) $("#gender").html(result.gender) $("#birthday").html(result.birthday) $("#phone").html(result.phone) $("#address").html(result.address) $("#userRoleName").html(result.userRoleName) }, error:function () { alert("error!") } }) })
controller代码
1 @RequestMapping(value = "/jsp/view/{id}",method = RequestMethod.GET) 2 @ResponseBody 3 //pathVariable接受外面的传过来的值,并且拼在路径的后面不会有?问号 4 public Object view(@PathVariable("id") String id){ 5 System.out.println(id); 6 //进行筛选的操作 7 User user = userService.getUserById(id); 8 if(user!=null){ 9 //返回一个json对象 10 return JSONArray.toJSONString(user); 11 }else{ 12 return JSONArray.toJSONString(new User()); 13 } 14 }
效果图:
列2:通过id删除,无刷新页面
1 $(".deleteUser").click(function () { 2 var id=$(this).attr("userid"); 3 var tr=$(this) 4 $.ajax({ 5 type:"get", 6 url:"/jsp/delete/"+id, 7 dataType:"json", 8 success:function (resutl) { 9 if(resutl.boolean=="true"){ 10 tr.parents("tr").remove(); 11 }else{ 12 alert("删除失败!") 13 } 14 15 }, 16 error:function () { 17 alert("error!") 18 } 19 20 }) 21 })
1 @RequestMapping(value = "/jsp/delete/{id}",method = RequestMethod.GET) 2 //@ResponseBody的作用其实是将java对象转为json格式的数据,注意:在使用 @RequestMapping后 3 @ResponseBody 4 public String delUser(@PathVariable("id") Integer delId) { 5 System.out.println("删除了Id为________:"+delId); 6 boolean b = userService.deleteUserById(delId); 7 Map<String,String> map=new HashMap<String,String>(); 8 if (b) { 9 System.out.println("成功"); 10 //给map设值,外面可以拿到boolean属性并且拿到value="true"进行判断 11 12 map.put("boolean","true"); 13 return JSONArray.toJSONString(map); 14 }else{ 15 System.out.println("失败"); 16 map.put("boolean","false"); 17 return JSONArray.toJSONString(map); 18 } 19 20 }
效果图,没删除之前:
删除后:
@RequestMapping(value = "/jsp/delete/{id}",method = RequestMethod.GET)
@ResponseBody
public String delUser(@PathVariable("id") Integer delId) {
System.out.println("删除了Id为________:"+delId);
boolean b = userService.deleteUserById(delId);
Map<String,String> map=new HashMap<String,String>();
if (b) {
System.out.println("成功");
map.put("boolean","true");
return JSONArray.toJSONString(map);
}else{
System.out.println("失败");
map.put("boolean","false");
return JSONArray.toJSONString(map);
}
}