源码下载
返回String
后台代码返回String类型
package controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class AjaxHandler { @RequestMapping(value = "/ajax.action", method = RequestMethod.POST, produces = "text/html;charset=UTF-8") @ResponseBody public String method1(HttpServletRequest request) { // 获得key为username的value String username = request.getParameter("username"); // 处理获得的参数 System.out.println(username); String reslut = "登录成功:" + username; // 返回结果 return reslut; } }
前台代码
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $(function() { /* Ajax post */ $('#submitbt').click(function() { var Username = $("#username").val(); $.post("ajax.action", { username : Username, }, function(data) { //从后台传过来的数据 alert(data); }); }); /* Ajax post */ }); </script> <body> <form action="" method="post"> username<input type="text" name="username" id="username" /> <input type="button" value="Ajax" id="submitbt"> </form> </body>
返回List<Student>
后台代码
@RequestMapping(value = "/ajaxList.action", produces = { "application/json;charset=UTF-8" }) @ResponseBody public List<Student> returnList(HttpServletRequest request) { System.out.println("从前台获取的参数:" + request.getParameter("username")); List<Student> students = new ArrayList<>(); Student stu1 = new Student(1, "张三"); Student stu2 = new Student(2, "李四"); Student stu3 = new Student(3, "王五"); students.add(stu1); students.add(stu2); students.add(stu3); return students; }
前台代码
$('#ajaxlist').click(function() { $.post("ajaxList.action", { username : '123'//这是地方是参数 }, function(data) { //从后台传过来的数据 字符串[{"id":1,"name":"张三"},{"id":2,"name":"李四"},{"id":3,"name":"王五"}] //开始解析List<Student> for(i=0;i<data.length;i++){ var str="<li value="+data[i].id+">"+data[i].id+data[i].name+"</li>"; $("#listStudent").append(str); } }); });
<h1>返回ListStudent</h1> <button id="ajaxlist">获取List</button> <ul id="listStudent"> <li>如下</li> </ul>
返回Map
后台代码
@RequestMapping(value = "/ajaxMap.action", produces = { "application/json;charset=UTF-8" }) @ResponseBody public Map<String, Object> returnMap() { Map<String, Object> maps = new HashMap<>(); maps.put("student", "张三"); maps.put("teacher", "李四"); return maps; }
$('#ajaxMap').click(function() { $.post("ajaxMap.action", { username : '123'//这是地方是参数 }, function(data) { //从后台传过来的数据 字符串{"teacher":"李四","student":"张三"} //开始解析Map<String> var str="<li value="+1+">"+data.student+"</li>"; $("#mapString").append(str); var str="<li value="+1+">"+data.teacher+"</li>"; $("#mapString").append(str); }); });
<h1>返回Map</h1> <button id="ajaxMap">获取Map</button> <ul id="mapString"> <li>如下</li> </ul>
出现406错误
少jar,去上面的项目里的lib下去找