Spring mvc AJAX技术实现原理解析

2020-03-19 16:02:41于海丽

@Controller
public class AjaxController {

  @RequestMapping("/a1")
  public void ajax1(String name , HttpServletResponse response) throws IOException {
    if ("admin".equals(name)){
      response.getWriter().print("true");
    }else{
      response.getWriter().print("false");
    }
  }

}

导入jquery , 可以使用在线的CDN , 也可以下载导入

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>

编写index.jsp测试

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
 <head>
  <title>$Title$</title>
  <%--<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>--%>
  <script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
  <script>
    function a1(){
      $.post({
        url:"${pageContext.request.contextPath}/a1",
        data:{'name':$("#txtName").val()},
        success:function (data,status) {
          alert(data);
          alert(status);
        }
      });
    }
  </script>
 </head>
 <body>

 <%--onblur:失去焦点触发事件--%>
 用户名:<input type="text" id="txtName" onblur="a1()"/>
 </body>
</html>

启动tomcat测试! 打开浏览器的控制台,当我们鼠标离开输入框的时候,可以看到发出了一个ajax的请求!是后台返回给我们的结果!测试成功!

SpringMVC实现

实体类user

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
  private String name;
  private int age;
  private String sex;

}

我们来获取一个集合对象,展示到前端页面

@RequestMapping("/a2")
public List<User> ajax2(){
  List<User> list = new ArrayList<User>();
  list.add(new User("黄大姐",25,"女"));
  list.add(new User("黄小姐",25,"女"));、
  return list; //由于@RestController注解,将list转成json格式返回
}

前端页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Title</title>
</head>
<body>
<input type="button" id="btn" value="获取数据"/>
<table width="80%" align="center">
  <tr>
    <td>姓名</td>
    <td>年龄</td>
    <td>性别</td>
  </tr>
  <tbody id="content">
  </tbody>
</table>

<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
<script>

  $(function () {
    $("#btn").click(function () {
      $.post("${pageContext.request.contextPath}/a2",function (data) {
        console.log(data)
        var html="";
        for (var i = 0; i <data.length ; i++) {
          html+= "<tr>" +
            "<td>" + data[i].name + "</td>" +
            "<td>" + data[i].age + "</td>" +
            "<td>" + data[i].sex + "</td>" +
            "</tr>"
        }
        $("#content").html(html);
      });
    })
  })
</script>
</body>
</html>