转自 https://blog.youkuaiyun.com/m0_37729679/article/details/78634069 如有侵权 请速联系我会及时删除
mavean依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.41</version> </dependency>
//映射一个action 这里一定要设置编码否则前台获取时会乱码 @RequestMapping(value = "/returnMap",produces="text/html;charset=UTF-8;") @ResponseBody//表示直接输出返回内容,不进行jsp或html跳转,本例是为了写接口,这里直接返回json public String returnMap() { //模拟数据库数据 Map map1 = new HashMap(); map1.put("sId","1001"); map1.put("sName","李俊成"); map1.put("sSex","男"); Map map2 = new HashMap(); map2.put("sId","1002"); map2.put("sName","伍天秀"); map2.put("sSex","女"); //转成json对象 String json = JSONArray.toJSONString(list); System.out.println(json); return json; }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Title</title> <!-- Jquery In Here --> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script> <script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="panel panel-warning" style="width: 50%; margin-left: 25%;margin-top: 10%"> <div class="panel-heading"> <h3 class="panel-title"> 查询信息 </h3> <br> <button id="thisList" class="btn btn-default">GetList</button> </div> <div class="panel-body"> <table class="table"> <thead> <tr> <th>学号</th> <th>姓名</th> <th>性别</th> </tr> </thead > <tbody id="resultTable"> </tbody> </table> </div> </div> </body> </html> <script type="text/javascript" charset="UTF-8"> $("#thisList").click(function () { $.ajax({ type: "POST", url: "/test/returnMap", error: function () { //服务器返回失败调用的方法 alert("error!---说明服务器返回失败"); }, dataType: "json", success: function (data) { //清除之前的结果 $("#resultTable").empty(); var thisListValueStr = ""; console.log(data.length+"条数据"); for (var i = 0; i < data.length; i++) { //解释一下data[i],第一个[i]是获得JSONArray中的第i个Map //如本方法caseList[0],是data中第一个list中的第一个Map var caseList = data[i]; //获取Map thisListValueStr = "<tr><td>" + caseList.sId + "</td><td>" + caseList.sName + "</td><"+ "<td>" + caseList.sSex + "</td></tr>"; $("#resultTable").append(thisListValueStr); thisListValueStr = ""; } } }); }); </script>