springmvc+jquery+json
LuisaDeloss
9年前
来自: http://my.oschina.net/craftsdream/blog/607095
前提是搭建好了是springmvc的环境和引入jquery
//这是jsp的代码 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>主页</title> <script type="text/javascript" src="/<%=request.getContextPath()%>/js/jquery-2.0.3.min.js"></script> </head> <body> this is a json.jsp! <hr> <a href="/springmvc/spring/spring/getChildren">jsontest</a> <input type="submit" onclick="jsontest()" value="json" > <script type="text/javascript"> function jsontest(){ $.ajax( { type : "get", url : "<%=request.getContextPath()%>/spring/spring/getChildren", dataType: "json", success : function(data) { alert("1:"+data[0].name); //jauery循环输出json数据 $.each(data,function(idx,item){ //输出 alert(item.name+"哈哈"+item.age); }) }, error :function(){ alert("2:网络连接出错!"); } }); } </script> </body> </html><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>主页</title> <script type="text/javascript" src="/springmvc/js/jquery-2.0.3.min.js"></script> </head> <body> this is a json.jsp! <hr> <a href="/springmvc/spring/spring/getChildren">jsontest</a> <input type="submit" onclick="jsontest()" value="json" > <hr> <textarea id="jsonv" rows="10" cols="100"></textarea> <script type="text/javascript"> function jsontest(){ $.ajax( { type : "get", url : "<%=request.getContextPath()%>/spring/spring/getChildren", dataType: "json", success : function(data) { //jauery循环输出json数据 $.each(data,function(idx,item){ //输出 var temp=$("#jsonv").val(); $("#jsonv").val(temp+","+item.name+":"+item.age); }) }, error :function(){ alert("2:网络连接出错!"); } }); } </script> </body> </html>
//这是controller的json数据传输 @RequestMapping("getChildren") public @ResponseBody String getChildren(Long objectId) throws Exception { List<Person> trees = new ArrayList<Person>(); for(int i=1;i<9;i++){ Person per=new Person("jack"+i,"1"+i); trees.add(per); } return parseJsonTree(trees); } private String parseJsonTree(List<Person> trees) { StringBuilder children = new StringBuilder(140 * trees.size()); children.append("["); int i=0; Gson gson = new GsonBuilder().create();//com.google.gson.Gson for ( Person tree : trees) { if(i>0){ children.append(","); } children.append(gson.toJson(tree)); i++; } children.append("]"); return children.toString(); }
结果:jack1:11,jack2:12,jack3:13,jack4:14,jack5:15,jack6:16,jack7:17,jack8:18