以下是基于 SpringBoot 和 AJAX 编写的判断表单中用户名是否存在的程序示例:

  1. 在 SpringBoot 项目中添加依赖

pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- 添加 Thymeleaf 模板引擎依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 创建实体类

创建一个 User 实体类,用于存储用户的信息:

public class User {
    private String username;
    private String password;
    // getter and setter methods
}
  1. 编写控制器

创建一个控制器类 UserController,编写一个 checkUsername 方法用于判断用户名是否存在:

@Controller
public class UserController {
    @GetMapping("/check-username")
    @ResponseBody
    public String checkUsername(String username) {
        // 此处省略获取用户的逻辑,假设用户已经存在
        return 'exist';
    }
}

在上面的代码中,我们使用了 @GetMapping 注解来指定请求的 URL,同时使用了 @ResponseBody 注解来标识返回的数据类型是 JSON。

  1. 编写模板文件

创建一个名为 index.html 的模板文件,其中包含一个用户名输入框和一个按钮:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>SpringBoot AJAX Demo</title>
</head>
<body>
    <form>
        <label>Username:</label>
        <input type="text" name="username" id="username">
        <button type="button" onclick="checkUsername()">Check</button>
    </form>
    <script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script>
        function checkUsername() {
            var username = $("#username").val();
            $.get("/check-username", {username: username}, function (data) {
                if (data === 'exist') {
                    alert('Username already exists!');
                } else {
                    alert('Username is available.');
                }
            });
        }
    </script>
</body>
</html>

在上面的代码中,我们使用了 Thymeleaf 模板引擎来渲染 HTML 页面,并使用了 jQuery 库来简化 AJAX 请求的过程。在点击按钮时,会调用 checkUsername 函数,该函数会获取用户名输入框的值,并使用 AJAX 发送 GET 请求到 /check-username URL,同时传递用户名参数。服务器会根据用户名是否存在返回不同的数据,前端再根据返回的数据来提示用户。

  1. 运行程序

运行 SpringBoot 程序后,访问 http://localhost:8080 即可看到页面。在用户名输入框中输入一个已经存在的用户名(比如 admin),点击按钮,会弹出一个提示框,显示用户名已经存在。输入一个不存在的用户名,会提示用户名可用。

基于 SpringBoot 使用 AJAX 实现表单用户名存在性校验

原文地址: https://www.cveoy.top/t/topic/noxu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录