SpringMVC学习(八)Ajax异步请求

文章目录

        • 一、Ajax简介( Asynchronous JavaScript and XML)
          • Ajax的使用场景:
        • 二、使用JQuery开发ajax
          • 搭建测试环境
          • 案例一:
          • 案例二:SpringMVC版
          • 案例三:注册账户提示

一、Ajax简介( Asynchronous JavaScript and XML)

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

搜索时搜索补全:
SpringMVC学习(八)Ajax异步请求_第1张图片

二、使用JQuery开发ajax

SpringMVC学习(八)Ajax异步请求_第2张图片

搭建测试环境
  1. 新建一个Module SpringMVC-Ajax
  2. 配置web.xml

<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-name>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:applicationContext.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    
    <filter>
        <filter-name>encodingfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>utf-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingfilter-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

<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/>
    
    <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>Ajaxtitle>
    <%--导入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学习(八)Ajax异步请求_第3张图片
案例二: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>Titletitle>
    <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 += "" +
                            "" + data[i].name + "" +
                            "" + data[i].age + "" +
                            "" + data[i].sex + "" +
                            ""
                    }
                    $("#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>

测试:
SpringMVC学习(八)Ajax异步请求_第4张图片
SpringMVC学习(八)Ajax异步请求_第5张图片

案例三:注册账户提示
  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>Titletitle>
    <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测试:
    SpringMVC学习(八)Ajax异步请求_第6张图片
    SpringMVC学习(八)Ajax异步请求_第7张图片

你可能感兴趣的:(SpringMVC学习(八)Ajax异步请求)