基于spring boot使用AJAX编写程序实现判断表单中的用户名是否存在
- 创建一个Spring Boot项目。
- 添加依赖:spring-boot-starter-web、spring-boot-starter-thymeleaf。
- 创建一个Controller类,用于处理请求和返回结果。
- 在Controller中添加一个RequestMapping注解,用于处理ajax请求。
- 在RequestMapping中添加一个@RequestBody注解,用于获取ajax请求中的数据。
- 在Controller中添加一个方法,用于判断用户名是否存在。
- 在方法中使用JdbcTemplate查询数据库,判断用户名是否存在。
- 根据查询结果,返回一个结果字符串。
- 在Thymeleaf页面中添加一个ajax请求,用于向Controller发送请求,判断用户名是否存在。
- 在页面中使用jQuery处理返回结果,显示提示信息。
示例代码如下:
Controller类:
@Controller
public class UserController {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping(value = "/checkUsername", method = RequestMethod.POST)
@ResponseBody
public String checkUsername(@RequestBody String username) {
String sql = "SELECT COUNT(*) FROM user WHERE username = ?";
int count = jdbcTemplate.queryForObject(sql, Integer.class, username);
if (count > 0) {
return "exist";
} else {
return "not exist";
}
}
}
Thymeleaf页面:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Check Username</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<form>
<label>Username:</label>
<input type="text" id="username" name="username">
<span id="result"></span>
</form>
<script>
$(function () {
$('#username').blur(function () {
$.ajax({
type: 'POST',
url: '/checkUsername',
contentType: 'application/json;charset=UTF-8',
data: JSON.stringify($(this).val()),
success: function (data) {
if (data === 'exist') {
$('#result').text('Username already exists');
} else {
$('#result').text('Username does not exist');
}
}
});
});
});
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/b3fS 著作权归作者所有。请勿转载和采集!