AJAX
前端用js写原生AJAX
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function getXhr(){ var xhr = new XMLHttpRequest xhr.open("POST", "/AjaxTest"); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ var text = xhr.responseText; } } xhr.send(); }
|
后端处理AJAX请求:
1 2 3 4 5 6
| resp.setContentType("appclication/json")
resp.getWriter().write("{\"name\":\"张三丰\",\"age\":22}"); resp.getWriter().flush(); resp.getWriter().close();
|
利用jQuery发送AJAX请求:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| $.ajax({ type : "" url : ""; contentType : "application/json;charset=UTF-8" data : ""; success : function(result){ console.log(result); }) error : function(e){ console.log(e.status); console.log(e.responseText); } })
|
jQuery针对与不同请求也提供了封装好的ajax请求:
1 2 3 4 5 6 7 8 9 10 11 12 13
| $.get("/url",param,function(result){ },"json")
$.getJSON("/url",param,function(result){ })
$.post("/url",param,function(result){ },"json")
|
后端响应异步请求,可以利用springmvc的@ResponseBody注解:
@ResponseBody是作用在方法上的,作用是将java对象转为json格式的数据,并把返回结果直接写入 HTTP response body 中。
1 2 3 4 5
| @ResponseBody @RequestMapping("/user") public List<User> findAll(){ return userService.findAll(); }
|