效果展示:
点击TEST按钮后会刷新下方表格,其余元素不动
点击后的效果
html部分
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<style>
td,th {
border: 1px solid black;
}
</style>
<script>
// 点击按钮后请求Ajax,成功后更新表格
function btnClick() {
$.ajax({
url : "/book_search",
type : "GET",
data : {"searchBook":"test"},
contentType:"application/x-www-form-urlencoded;charset=UTF-8",
success : function (data) {
$(".book_recorde").html(data);
},
error:function (errorMsg) {
console.log(errorMsg);
}
})
}
</script>
<body>
<div>
<button type="button" onclick="btnClick()">TEST</button>
</div>
<div class="book_recorde" th:fragment="book_recorde">
<table id="myTable">
<tr>
<th>Name</th>
<th>Value</th>
</tr>
<!-- 表格更新的部分 -->
<tr th:each="bookRecorde:${bookRecordes}">
<td th:text="${bookRecorde.bookName}"></td>
<td th:text="${bookRecorde.num}"></td>
</tr>
</table>
</div>
</body>
</html>
后端Controller进入点
package com.example.vuebackend.controller;
import com.example.vuebackend.dto.BookNumInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.List;
@Controller
public class BookController {
List<BookNumInfo> list = new ArrayList<>();
int count = 1;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
return "index";
}
// 进入后更新数组中元素,并返回数据
@RequestMapping(value = "/book_search", method = RequestMethod.GET)
public String queryBook(@RequestParam(value = "searchBook") String searchBook, Model model){
list.clear();
for (int i = 0; i < 5; i++) {
list.add(new BookNumInfo("Name" + count,"" + count++));
}
// 返回数据
model.addAttribute("bookRecordes",list);
return "index::book_recorde";
}
}
对应的Dto
package com.example.vuebackend.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class BookNumInfo {
String bookName;
String num;
}