JavaEE——SpringMVC(8)--处理 JSON:使用 HttpMessageConverter 可做下载
ajax $.ajax()方法详解
使用@ResponseBody注解
从后台获取List<Blog> 传递给前端。并解析
@RequestMapping(value = "/testJson", method = RequestMethod.POST) public @ResponseBody List<Blog> testJson(HttpServletRequest request){ String id = request.getParameter( "id" ); Integer userId = Integer.valueOf( id ); List<Blog> blog = blogService.findAllBlogByUserId( userId ); /*JSONArray jsonArray = JSONArray.fromObject(blog);*/ /*JSONObject jsonObject = JSONObject.fromObject( blog );*/ return blog; }
前端将获取到的List数据解析为想要的格式
可使用JavaScript JSON.stringify() 来进行
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <p id="demo"></p> <script> var str = {"name":"菜鸟教程", "site":"http://www.runoob.com"} str_pretty1 = JSON.stringify(str) document.write( "只有一个参数情况:" ); document.write( "<br>" ); document.write("<pre>" + str_pretty1 + "</pre>" ); document.write( "<br>" ); str_pretty2 = JSON.stringify(str, null, 4) //使用四个空格缩进 document.write( "使用参数情况:" ); document.write( "<br>" ); document.write("<pre>" + str_pretty2 + "</pre>" ); // pre 用于格式化输出 </script> </body> </html>
输出结果
只有一个参数情况: {"name":"菜鸟教程","site":"http://www.runoob.com"} 使用参数情况: { "name": "菜鸟教程", "site": "http://www.runoob.com" }
<button id="blogType">test Json</button> <script> document.getElementById('blogType').addEventListener('click', function () { var userId = <%--${sessionScope.user.id};--%> $.ajax({ type: "post", url: "/blogType/allBlogType", data: {id:JSON.stringify(userId)}, dataType: "json", // contentType: "application/json", success: function(data){ $.each(data, function(i, item){ var json1 = JSON.stringify(item, null, 4); console.log(json1); $.each(item, function(j, val){ }); }); } }); }, false) </script>
在Controller处
@Controller @RequestMapping("/blogType") public class BlogTypeController { @Autowired BlogTypeService blogTypeService; @RequestMapping(value = "/allBlogType") public @ResponseBody List<BlogType> allBlogType(HttpServletRequest request){ String id = request.getParameter( "id" ); Integer userId = Integer.parseInt(id); List<BlogType> blog = blogTypeService.allBlogType( userId ); for(BlogType i : blog){ System.out.println(i); } return blog; } }