探究AJAX

AJAX简介

AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。

AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。

Ajax 不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的Web应用程序的技术

  • 在 2005 年,Google 通过其 Google Suggest 使 AJAX 变得流行起来。Google Suggest能够自动帮你完成搜索单词。
  • Google Suggest 使用 AJAX 创造出动态性极强的 web 界面:当您在谷歌的搜索框输入关键字时,JavaScript 会把这些字符发送到服务器,然后服务器会返回一个搜索建议的列表,就和国内百度的搜索框一样!
  • 传统的网页(即不用ajax技术的网页),想要更新内容或者提交一个表单,都需要重新加载整个网页。
  • 使用ajax技术的网页,通过在后台服务器进行少量的数据交换,就可以实现异步局部更新。
  • 使用Ajax,用户可以创建接近本地桌面应用的直接、高可用、更丰富、更动态的Web用户界面。

AJAX运用场景:

  • 注册时,输入用户名自动检测用户是否已经存在
  • 登陆时,提示用户名密码错误
  • 删除数据行时,将行ID发送到后台,后台在数据库中删除,数据库删除成功后,在页面DOM中将数据行也删除等等

使用JQuery.ajax

使用jquery提供的,方便学习和使用,避免重复造轮子

Ajax的核心是XMLHttpRequest对象(XHR)。XHR为向服务器发送请求和解析服务器响应提供了接口。能够以异步方式从服务器获取新数据

例如:访问百度,右键打开检查打开开发者调试工具可以看到许多类型为XHR的AJAX异步请求数据

在这里插入图片描述

jQuery 提供多个与 AJAX 有关的方法,
通过 jQuery AJAX 方法,您能够使用 HTTP Get 和 HTTP Post 从远程服务器上请求文本、HTML、XML 或 JSON ,同时您能够把这些外部数据直接载入网页的被选元素中,jQuery Ajax本质就是 XMLHttpRequest,对他进行了封装,方便调用

可以看看JQuery中ajax的源码

jQuery.ajax(...)
      部分参数:
            url:请求地址
            type:请求方式,GETPOST1.9.0之后用method)
        headers:请求头
            data:要发送的数据
    contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
          async:是否异步
        timeout:设置请求超时时间(毫秒)
      beforeSend:发送请求前执行的函数(全局)
        complete:完成之后执行的回调函数(全局)
        success:成功之后执行的回调函数(全局)
          error:失败之后执行的回调函数(全局)
        accepts:通过请求头发送给服务器,告诉服务器当前客户端可接受的数据类型
        dataType:将服务器端返回的数据转换成指定类型
          "xml": 将服务器端返回的内容转换成xml格式
          "text": 将服务器端返回的内容转换成普通文本格式
          "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
        "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
          "json": 将服务器端返回的内容转换成相应的JavaScript对象
        "jsonp": JSONP 格式使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数

测试一:使用最原始的HttpServletResponse处理,最简单 , 最通用

扫描二维码关注公众号,回复: 12918666 查看本文章
  1. 配置web.xml和springmvc的配置文件

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">

    <!--1.注册DispatcherServlet-->
    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--关联一个springmvc的配置文件:-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!--启动级别-1-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <!--/ 匹配所有的请求;(不包括.jsp)-->
        <!--/* 匹配所有的请求;(包括.jsp)-->
        <servlet-name>spring-mvc</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>

springmvc.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:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://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/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--开启mvc注解驱动-->
    <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>
<!--让Spring MVC不处理静态资源-->
    <mvc:default-servlet-handler/>
<!--自动扫描包,让指定包下的注解生效,由SpringIOC容器统一管理 -->
    <context:component-scan base-package="com.chenhui.controller"/>


<!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--    前缀    -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--        后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
  1. 编写一个AJAXController类
@Controller
public class AJAXController {
    
    


    @RequestMapping("/test1")
    public void test1(String name, HttpServletResponse response) throws IOException {
    
    
        if ("admin".equals(name)){
    
    
            response.getWriter().println("ok");
        }else {
    
    
            response.getWriter().println("error");
        }
    }
}    
  1. 导入JQuery文件,可以使用CDN也可以下载导入
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.0.min.js"></script>
  1. 编写test1.jsp页面
<%--
  Created by IntelliJ IDEA.
  User: LEGION
  Date: 2021/3/11
  Time: 11:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%--    表单--%>
<%--onblur:失去焦点触发事件,输入框失去焦点调用test()方法--%>
    用户名:<input type="text" id="txName" onblur="test()">

    <script>

        function test(){
    
    
            //调用jquery的AJAX方法
            $.post({
    
    
              //访问请求路径  
              url :"${pageContext.request.contextPath}/test1",
              //携带data数据参数  
              data:{
    
    
                  "name": $("#txName").val()
              },
              //访问成功返回后台数据  
              success: function (data) {
    
    
                    alert(data);
              }
            })
        };
    </script>
<%--引入jquery文件--%>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>

</body>
</html>

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

在这里插入图片描述

使用SpringMVC实现

  1. 新建一个实体类Book
public class Book implements Serializable {
    
    

    private int id;
    private String name;
    private Double price;

    public Book(int id, String name, Double price) {
    
    
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public Book() {
    
    
    }

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public Double getPrice() {
    
    
        return price;
    }

    public void setPrice(Double price) {
    
    
        this.price = price;
    }

    @Override
    public String toString() {
    
    
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }


}

  1. 编写Controller类,获取一个集合对象,展示到前端页面
@ResponseBody
    @RequestMapping("/test2")
    public List<Book> test2(){
    
    
        //创建一个集合存储对象
        ArrayList<Book> list = new ArrayList<>();
        Book book1 = new Book(1, "java", 20.2);
        Book book2 = new Book(2, "mysql", 40.2);
        Book book3 = new Book(3, "python", 60.2);
        list.add(book1);
        list.add(book2);
        list.add(book3);
        //由于@ResponseBody注解,list集合将转化为json对象返回
        return list;
    }
  1. 编写test2.jsp页面
<%--
  Created by IntelliJ IDEA.
  User: LEGION
  Date: 2021/3/11
  Time: 12:11
  To change this template use File | Settings | File Templates.
--%>
<%@ 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}/static/js/jquery-3.6.0.js"></script>
<script>
<%--        绑定输入框标签并且触发点击事件--%>
        $("#btn").click(function () {
    
    
            //使用JQuery的AJAX方法异步请求
            $.get({
    
    
                //请求地址为
                url :"${pageContext.request.contextPath}/test2",
                //请求成功返回json数据
                success:function (data) {
    
    
                    //将数据拼接成HTML标签
                    var html=""
                    for (let i = 0; i <data.length ; i++) {
    
    
                        html+="<tr>"+
                            "<td>"+data[i].id+"</td>"+
                            "<td>"+data[i].name+"</td>"+
                            "<td>"+data[i].price+"</td>"+
                            "</tr>"
                    }
                    //获取tbody标签进行嵌入标签
                    $("#content").html(html);
                }
            });
        })

</script>
</body>
</html>

  1. 测试结果:
    在这里插入图片描述
    点击按钮:
    在这里插入图片描述
    测试三:实现输入框失去焦点时自动判断用户名和密码是否正确

  2. 编写一个Controller类:

//@ResponseBody该注解表示返回类型为json数据类型
    @ResponseBody
    @PostMapping("/test3")
    public String test3(@Param("username") String username,@Param("password") String password){
    
    
        String msg="";
        if (username!=null) {
    
    
//            模拟数据库中的用户名
            if ("admin".equals(username)) {
    
    
                msg = "ok";
            } else {
    
    
                msg = "用户名输入错误";
            }
        }
        if (password!=null){
    
    
//            模拟数据库中的密码
            if ("123456".equals(password)){
    
    
                msg="ok";
            }else {
    
    
                msg="密码输入错误";
            }
        }
//返回消息msg做为json数据
        return msg;
    }
  1. 编写test3.jsp页面
<%--
  Created by IntelliJ IDEA.
  User: LEGION
  Date: 2021/3/11
  Time: 15:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--οnblur="u()"表示失去焦点时触发u()事件--%>
用户名:<input type="text" name="username" id="name" onblur="u()" >
<%--用来显示用户名是否正确信息--%>
<span id="userInfo"></span>
<p></p>
密码:<input type="password" name="password" id="pwd" onblur="p()">
<span id="pwdInfo"></span>
<%--引入JQuery库--%>
<script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>

<script>
    function u(){
     
     
        $.post({
     
     
            url:"${pageContext.request.contextPath}/test3",
        //传入输入框username的值作为参数
            data:{
     
     
                "username":$("#name").val()
            },
            //成功请求时执行success回调函数(传入data的json数据)
            success: function (data) {
     
     
                //判断返回的msg的json数据
                if (data.toString()=="ok"){
     
     
                    //如果为"ok"则显示ok
                    $("#userInfo").css("color","green");
                }else {
     
     
                    $("#userInfo").css("color","red");
                }
                //否则返回红色错误信息
                $("#userInfo").html(data);
            }
        })
    }
    function p(){
     
     
        $.post({
     
     
            url:"${pageContext.request.contextPath}/test3",
            //传入输入框password的值作为参数
            data:{
     
     
                "password":$("#pwd").val()
            },
            //成功请求时执行success回调函数(传入data的json数据)
            success: function (data) {
     
     
                //判断返回的msg的json数据
                if (data.toString()=="ok"){
     
     
                    //如果为"ok"则显示ok
                    $("#pwdInfo").css("color","green");
                }else {
     
     
                    //否则返回红色错误信息
                    $("#pwdInfo").css("color","red");
                }
                $("#pwdInfo").html(data);
            }
        })
    }

</script>

</body>
</html>

  1. 结果(处理json乱码问题):异步请求结果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45608165/article/details/115062682
今日推荐