Ajax

Ajax

异步无刷新请求

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

依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.9.RELEASE</version>
</dependency>
<!--Servlet - JSP -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.24</version>
</dependency>
<!-- JSON -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.14.2</version>
</dependency>

伪Ajax

  • 点击按钮后,iframe加载url填写的页面
  • 模拟异步请求
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>iframe测试体验页面无刷新</title>

    <script>
        function go() {
            document.getElementById("iframe1").src = document.getElementById("url").value;
        }
    </script>
</head>
<body>
    <div>
        <p>请输入地址: </p>
        <p>
            <input type="text" id="url">
            <input type="button" value="提交" onclick="go()">
        </p>
    </div>
    <div>
        <iframe id="iframe1" src="" style="width: 100%;height: 500px"></iframe>
    </div>
</body>
</html>

jQuery.ajax

  • jQuery是一个库
  • jQuery 提供多个与 AJAX 有关的方法
  • 通过 jQuery AJAX 方法,能够使用 HTTP Get 和 HTTP Post 从远程服务器上请求文本、HTML、XML 或 JSON
  • 同时能够把这些外部数据直接载入网页的被选元素中

CDN

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

参数

jQuery.ajax(...)
      部分参数:
            url:请求地址  !!!
           type:请求方式,GET、POST(1.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 将自动替换 ? 为正确的函数名,以执行回调函数

样例

  • 首先请求/t1跳转到index.jsp页面
  • input框内输入文本
  • 通过ajax异步判断文本是否符合要求
  • 最后通过弹窗True/False显示结果

AjaxController.java

@Controller
public class AjaxController {
    @RequestMapping("/t1")
    public String test() {
        return "index";
    }

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

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>
        function a1() {
            $.post({
                url: "${pageContext.request.contextPath}/a1",
                data: {"name" : $("#username").val()},
                success: function (data) {
                    alert(data);
                }
            })
        }
    </script>
</head>

<body>
    <a href="${pageContext.request.contextPath}/t1"></a>
    用户名:<label for="username"></label><input type="text" id="username" onblur="a1()">
</body>
</html>

SpringMVC样例

  • 通过点击按钮,异步获取User列表,最后将获取到的列表数据展示在table

User.java

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

AjaxController.java

返回List类型需要添加Jackson依赖

@Controller
public class AjaxController {
    @ResponseBody
    @RequestMapping("/a2")
    public List<User> a2() {
        List<User> userList = new ArrayList<>();
        userList.add(new User("LCT1号",3,"男"));
        userList.add(new User("LCT2号",3,"男"));
        userList.add(new User("LCT3号",3,"男"));
        return userList;
    }
}

test.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>
        $(function () {
            $("#btn").click(function() {
                $.post({
                    url: "${pageContext.request.contextPath}/a2",
                    success: function(data) {
                        let txt = "";
                        for (let i = 0; i < data.length; i++) {
                            txt += "<tr>";
                            txt += "<td>" + data[i].name + "</td>";
                            txt += "<td>" + data[i].age + "</td>";
                            txt += "<td>" + data[i].sex + "</td>";
                            txt += "</tr>";
                        }
                        $("#content").html(txt);
                    }
                });
            });
        });
    </script>
</head>
<body>
<label>
    <input type="button" value="加载数据" id="btn">
</label>
<table>
        <tr>
            <td>姓名</td>
            <td>年龄</td>
            <td>性别</td>
        </tr>
        <tbody id="content">

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

效果

img

用户名验证样例

  • 第一个样例的延伸
  • 异步判断两个文本框的内容是否符合要求
  • 根据判断结果在文本框后面显示信息来提示用户

AjaxController.java

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

login.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>
        function a1() {
            $.post({
                url: "${pageContext.request.contextPath}/a3",
                data: {"name": $("#name").val()},
                success: function (data) {
                    let userInfo = $("#userInfo");
                    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: {"password": $("#pwd").val()},
                success: function (data) {
                    let pwdInfo = $("#pwdInfo");
                    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>

问题

  • 可能会遇到JSON处理后的字符串乱码

  • 使用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>
    

效果

img
posted @ 2023-07-04 20:12  James-Allen  阅读(36)  评论(0)    收藏  举报