SpringMVC——Ajax

异步无刷新请求

搭建环境后下载jQuery包,也可以用cdn库

注意controller类添加注解@RestController,禁止跳入视图

Demo01

前端页面:

 <%--
   Created by IntelliJ IDEA.
   User: 92397
   Date: 2020/9/10
   Time: 12:32
   To change this template use File | Settings | File Templates.
 --%>
 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 <html>
   <head>
     <title>首页</title>
     <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
     <script>
       function a(){
         $.post({
           url:"${pageContext.request.contextPath}/a1",
           data:{"name":$("#username").val()},
           success:function (data,status){
             console.log("data="+data);
             console.log("status="+status);
          },
           error:function (){
 
          }
        })
      }
     </script>
   </head>
   <body>
 
  <%--失去焦点的时候发起一个请求到后台--%>
  用户名:<input type="text" id="username" onblur="a()">
 
   </body>
 </html>

controller方法:

 //ajax测试1
 @RequestMapping("/a1")
 public void a1(String name, HttpServletResponse response) throws IOException {
     System.out.println("a1:param=>"+name);
     if ("lulu".equals(name)) {
         response.getWriter().print("true");;
    }else{
         response.getWriter().print("false");
    }
 }

最终效果:鼠标移开输入框后,会进入controller方法中进行判断,将结果返回前端。

 

 

 

Demo02 Ajax获得实体对象

构建一个实体类User

前端:

 <%--
   Created by IntelliJ IDEA.
   User: 92397
   Date: 2020/9/10
   Time: 14:19
   To change this template use File | Settings | File Templates.
 --%>
 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 <html>
 <head>
     <title>Title</title>
     <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
 
     <script>
         $(function (){
             $("#btn").click(function (){
                 $.post("${pageContext.request.contextPath}/a2",function (data){
                     //console.log(data);
                     let html="<>";
                     for (let i = 0; i < data.length; i++) {
                         html += "<tr>" +
                             "<td>"+data[i].name + "</td>" +
                             "<td>"+data[i].age + "</td>" +
                             "<td>"+data[i].gender + "</td>" +
                             "</tr>"
                    }
                     $("#userContent").html(html);
                })
            })
        })
     </script>
 </head>
 <body>
 <input type="button" value="加载数据" id="btn">
 <table>
     <tr>
         <td>姓名</td>
         <td>年龄</td>
         <td>性别</td>
     </tr>
     <tbody id="userContent">
     </tbody>
 </table>
 
 </body>
 </html>

controller方法:

 //ajax测试2
 @RequestMapping("/a2")
 public List<User> a2(){
     List<User> userList = new ArrayList<User>();
     //添加数据
     userList.add(new User("lulu",21,"女"));
     userList.add(new User("uletay",22,"女"));
     userList.add(new User("sll",23,"女"));
     //返回数据
     return userList;
 }

最终效果:点击加载数据按钮,调用controller中对应的方法并将实体对象返回前端展示

 点击前:

 

点击后:

 

Demo03 Ajax实现数据判断

前端:

 <%--
   Created by IntelliJ IDEA.
   User: 92397
   Date: 2020/9/10
   Time: 14:37
   To change this template use File | Settings | File Templates.
 --%>
 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 <html>
 <head>
     <title>Title</title>
     <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
     <script>
         function a1(){
             $.post({
                 url : "${pageContext.request.contextPath}/a3",
                 data : {"name" : $("#name").val()},
                 success : function (data){
                     if(data.toString()==="ok"){
                         $("#userInfo").css("color","green");
                    }else{
                         $("#userInfo").css("color","red");
                    }
                     $("#userInfo").html(data);
                },
            })
        }
         function a2(){
             $.post({
                 url : "${pageContext.request.contextPath}/a3",
                 data : {"pwd" : $("#pwd").val()},
                 success : function (data){
                     if(data.toString()==="ok"){
                         $("#pwdInfo").css("color","green");
                    }else{
                         $("#pwdInfo").css("color","red");
                    }
                     $("#pwdInfo").html(data);
                },
            })
        }
     </script>
 </head>
 <body>
 <p>
    用户名:<input type="text" id="name" onblur="a1()">
     <span id="userInfo"></span>
 </p>
 <p>
    密码:<input type="text" id="pwd" onblur="a2()">
     <span id="pwdInfo"></span>
 </p>
 </body>
 </html>

controller方法:

 @RequestMapping("/a3")
 public String a3(String name,String pwd){
     String msg;
     if("admin".equals(name)){
         msg = "ok";
    }else{
         msg = "用户名有误";
    }
     if(pwd!=null){
         if("123456".equals(pwd)){
             msg = "ok";
        }else {
             msg = "密码有误";
        }
    }
     return msg;
 }

处理乱码问题:springmvc配置文件中加上:

 <!--Json乱码-->
 <mvc:annotation-driven>
     <mvc:message-converters register-defaults="true">
         <bean class="org.springframework.http.converter.StringHttpMessageConverter">
             <property name="supportedMediaTypes">
                 <list>
                     <value>text/html;charset=UTF-8</value>
                     <value>application/json;charset=UTF-8</value>
                 </list>
             </property>
         </bean>
     </mvc:message-converters>
 </mvc:annotation-driven>

最终效果:

 

 

posted @ 2020-09-10 17:16  Fabulo  阅读(346)  评论(0)    收藏  举报