SpringMVC学习(八)Ajax异步请求

一、Ajax简介( Asynchronous JavaScript and XML)
  • Ajax就是在无需重新加载网页的情况下,能够部分更新网页的技术。
  • Ajax 不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的Web应用程序的技术。
  • 使用ajax技术的网页,通过在后台服务器进行少量的数据交换,就可以实现异步局部更新。
  • 使用Ajax,用户可以创建接近本地桌面应用的直接、高可用、更丰富、更动态的Web用户界面。
Ajax的使用场景:

搜索时搜索补全:
在这里插入图片描述

二、使用JQuery开发ajax

在这里插入图片描述

搭建测试环境
  1. 新建一个Module SpringMVC-Ajax
  2. 配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--配置servlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--设置编码-->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>
  1. 新建一个pojo和controller
//pojo
package com.zyh.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
    private String sex;
}
//controller
package com.zyh.controller;

import org.springframework.web.bind.annotation.RestController;

@RestController
public class AjaxController {
}
  1. 创建Spring配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--需要配置的->注解驱动、静态资源过滤、视图解析器 -->
    <context:component-scan base-package="com.zyh.controller"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>
    <!--处理JSON乱码-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
案例一:
  1. 编写AjaxController
    @RequestMapping("/t2")
    public void test2(String name, HttpServletResponse response) throws IOException {
        System.out.println("parm=>" + name);
        if ("zyh".equals(name)) {
            response.getWriter().print(true);
        } else {
            response.getWriter().print(false);
        }
    }
  1. 编写index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Ajax</title>
    <%--导入jquery--%>
    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>
    <script>
        function a() {
            $.post({
                url: "${pageContext.request.contextPath}/t2",
                data: {"name": $("#username").val()},
                success: function (data, status) {
                    console.log("data=>" + data);
                    console.log("status=>" + status);
                }
            })
        }
    </script>
</head>
<body>
<%--丢失鼠标焦点的事件--%>
<input type="text" id="username" onblur="a()">
</body>
</html>
  1. 启动Tomcat测试
    结果:
    在这里插入图片描述
案例二:SpringMVC版
  1. 编写实体类:User
package com.zyh.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

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

  1. 编写controller
    @RequestMapping("/t3")
    public List<User> test3() {
        List<User> userList = new ArrayList<User>();
        userList.add(new User("德莱厄斯", 22, "男"));
        userList.add(new User("厄斐琉斯", 16, "男"));
        userList.add(new User("马尔扎哈", 999, "男"));
        return userList;
    }
  1. 编写页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>
    <script>
        $(function () {
            $("#btn").click(function () {
                $.post("${pageContext.request.contextPath}/t3", function (data) {
                    var html = "";
                    for (let 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>
</head>
<body>
<input type="button" id="btn" value="加载数据">
<table>
    <tr>
        <td>姓名</td>
        <td>年龄</td>
        <td>性别</td>
    </tr>
    <%--加载后台数据--%>
    <tbody id="content">

    </tbody>
</table>
</body>
</html>

测试:
在这里插入图片描述
在这里插入图片描述

案例三:注册账户提示
  1. 编写Controller
    @RequestMapping("/t4")
    public String test4(String name, String password) {
        String msg = "";
        if (name != null) {
            if ("admin".equals(name)) {
                msg = "OK";
            } else {
                msg = "输入的用户名错误!";
            }
        }
        if (password != null) {
            if ("123456".equals(password)) {
                msg = "OK";
            } else {
                msg = "输入的密码错误!";
            }
        }
        return msg;
    }
  1. 编写前端页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src=${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js></script>
    <script>
        function a1() {
            $.post({
                url: "${pageContext.request.contextPath}/t4",
                data: {"name": $("#username").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}/t4",
                data: {"password": $("#password").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="username" onblur="a1()">
    <span id="userInfo"></span>
</p>
<p>
    密码<input type="text" id="password" onblur="a2()">
    <span id="pwdInfo"></span>
</p>
</body>
</html>
  1. 启动Tomcat测试:
    在这里插入图片描述
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值