我使用的是SpringBoot y百里叶。
如何在页面加载时在index.html中显示产品列表?
目前,products.html显示所有来自bd的产品,index.html显示带有products.html格式标题的片段,但我不知道如何制作来显示这些产品。
如果我的方法错了,正确的方法是什么呢?
index.html
<body>
<section layout:fragment="custom-content">
<br> <br>
<div class="container">
<section th:replace="products :: content"></section>
<br> <br>
<h2>This is index.html</h2>
</div>这是带有products.html片段index.html的index.html
products.html
<body>
<div class="container">
<div th:fragment="content">
<h3>This is the fragment from products.html</h3>
<h2>List of products</h2>
<table class="table table-stripped">
<tr>
<th>Id</th>
<th>Description</th>
<th>Price</th>
<th>Image Url</th>
<th>List</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr th:each="product : ${products}">
<td th:text="${product.id}"></td>
<td th:text="${product.description}"></td>
<td th:text="${product.price}"></td>
<td th:text="${product.imageUrl}"></td>
<td><a th:href="${'/products/numArt/' + product.numArt}">View</a></td>
<td><a>Edit</a></td>
<td><a>Delete</a></td>
</tr>
</table>
<div class="row">
<div class="col-sm-3">
<button>New Product</button>
</div>
</div>
</div>
</div>
这是products.html products.html
控制器
@GetMapping("/products")
public String listProducts(Model model) {
System.out.println("Get all products...");
model.addAttribute("products", productRepository.findAll());
return "products";
}发布于 2019-02-19 13:47:23
您绑定的是products.html中的products对象,而不是片段。因此,创建另一个类似于下面的方法。
@GetMapping("/products/fragment")
public ModelAndView listOfProducts() {
ModelAndView mv = new ModelAndView("index::custom-content");
mv.addObject("products", productRepository.findAll());
return mv;
}在你的index.html中通过ajax调用它。在索引文件中添加以下行
<script th:inline="javascript">
$(document).ready(function () {
loadData();
});
function loadData(){
$.ajax({
type: 'get',
url: /*[[ @{'/product/fragment'} ]]*/,
success: function(data){
$('.container').html(data);
},
async:false
})
}
</script><body>
<section >
<br> <br>
<div class="container">
<div th:fragment="custom-content">
<section th:replace="products :: content"></section>
<br> <br>
<h2>This is index.html</h2>
</div>
</div>
</section>....
希望这能有所帮助。
https://stackoverflow.com/questions/54749766
复制相似问题