如题,在springboot项目中如何让模态框动态获取列表信息。
首先@Controller中
@GetMapping("/")
public String index(HttpServletRequest request, Model model) throws Exception {
List AllStudent = studentServices.getallStudent();
List PassStudent = studentServices.getallPassStudent();
model.addAttribute(“AllStudent”, AllStudent);
model.addAttribute(“PassStudent”, PassStudent);
System.out.println(user);
model.addAttribute(“User”, user);
model.addAttribute(“StudentAccount”, studentServices.getStudentAccount());
model.addAttribute(“DiplomaAccount”, PassStudent.size());
String login = “Login in”;
if (IsLogin())
login = “Sign out”;
model.addAttribute(“Login”, login);
return “student/index”;
}
HTML中:
前端代码不好粘贴直接放图。
其中button用th:data-whatever记下主键以方便后面的查询。
JS:
$(’#showModel’).on(‘show.bs.modal’, function (event) {
var button = $(event.relatedTarget); // 触发事件的按钮
var id = button.data(‘whatever’);// 解析出data-whatever内容
var modal = $(this);
$.ajax({
url: “/student/getStudentByID/” + id,
type: “get”,
dataType: “json”,
success: function (date) {
modal.find(’#showStudentID’).val(date.id);
modal.find(’#showStudentName’).val(date.name);
modal.find(’#showStudentPassword’).val(date.password);
modal.find(’#showStudentSid’).val(date.sid);
modal.find(’#showStudentSchool’).val(date.school);
modal.find(’#showStudentMajor’).val(date.major);
modal.find(’#showStudentEduType’).val(date.eduType);
modal.find(’#showStudentEduHash’).val(date.eduHash);
modal.find(’#showStudentTime’).val(date.time);
}
})
})
这是模态框获取值,反之获取后我又要把值更改传回控制器从而修改数据呢?
在前端html加一个用于修改的按钮id=Update
JS:
$(’#Update’).click(function () {
var updateData = $("#showStudent").serializeArray();
var data = “{”;
for (var i = 0; i < updateData.length; i++) {
var name = updateData[i].name;
var value = updateData[i].value;
data = data + “”" + name + “”:"" + value.trim() + “”,";
}
data = data.substring(0, data.length - 1);
data = data + “}”;
console.log(data);
$.ajax({
url: “/student/personal”,
contentType: ‘application/json’,
dataType: “json”,
type: “post”,
data: data,
success: function (status) {
if (status.code == 1) {
alert(“update success”);
window.location.reload();
} else {
alert(“update failed”);
}
},
error: function (data) {
$(’#updateModal’).modal(‘hide’);
alert(“update error”);
window.location.reload();
}
});
注:Controller必须要有post的修改方法、name的命名要和你实体类Student的属性要一致方便注入
@Controller的方法:
@PostMapping("/student/personal")
public Response updateUser(@RequestBody Student student) throws Exception {
//代码
}
以下效果图: