thymleaf Boot 写新增弹窗,调用get请求addUser()获取数据
时间: 2023-07-19 10:11:25 浏览: 49
Thymeleaf Boot结合Controller和JavaScript可以实现弹窗新增数据的功能,具体步骤如下:
1. 在Controller中定义请求处理方法addUser(),用于返回新增用户的表单页面:
```java
@GetMapping("/addUser")
public String addUser(Model model) {
// TODO: 获取需要展示在表单中的数据
model.addAttribute("data", data);
return "addUser";
}
```
在上面的代码中,通过Model将需要展示在表单中的数据传递给Thymeleaf视图。
2. 在Thymeleaf视图中定义弹窗新增用户的表单:
```html
<div id="addModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>新增用户</h2>
<form id="addUserForm" th:action="@{/saveUser}" method="post">
<div>
<label>名称:</label>
<input type="text" name="name" th:value="${data.name}" />
</div>
<div>
<label>年龄:</label>
<input type="text" name="age" th:value="${data.age}" />
</div>
<button type="submit">保存</button>
</form>
</div>
</div>
```
在上面的代码中,定义了一个id为addModal的模态框,包含一个表单用于新增用户信息。表单的action属性指向Controller中处理保存请求的方法,使用Thymeleaf表达式动态绑定需要展示的数据。
3. 在JavaScript文件中定义showAddModal()函数,用于弹出新增用户的模态框:
```javascript
function showAddModal() {
$.get("/addUser", function(data) {
$("body").append(data);
$("#addModal").show();
$(".close").click(function() {
$("#addModal").remove();
});
});
}
```
在上面的代码中,通过jQuery的get()方法向Controller中的addUser()方法发起请求,获取新增用户的表单页面。请求成功后,将页面动态添加到body元素中,并显示模态框。同时,为关闭按钮添加了点击事件,当点击关闭按钮时,会将模态框从页面中移除。
4. 在HTML中定义新增按钮,并为其添加一个点击事件,调用showAddModal()函数弹出模态框:
```html
<button id="addButton" onclick="showAddModal()">新增</button>
```
通过以上步骤,即可实现利用Thymeleaf Boot结合Controller和JavaScript实现弹窗新增数据的功能,同时调用get请求addUser()获取数据。