You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JPA多对多关联场景下Thymeleaf实现分类-商品级联下拉选择方案问询

两级联动下拉框实现方案

1. 后端新增查询接口

首先新增接口用于根据分类ID返回对应商品列表:

Controller层代码

@RestController
@RequestMapping("/common-api")
public class CommonQueryController {

    @Resource
    private ProductRepository productRepository;

    @GetMapping("/list-product-by-category")
    public List<Product> listProductByCategoryId(@RequestParam Long categoryId) {
        return productRepository.findAllByProductCategoryId(categoryId);
    }
}

Repository层代码

在ProductRepository中新增查询方法:

public interface ProductRepository extends JpaRepository<Product, Long> {
    // 根据分类ID查询该分类下所有商品
    List<Product> findAllByProductCategoryId(Long categoryId);
}

如果使用Spring Security权限框架,需要将/common-api/list-product-by-category接口加入白名单,避免权限拦截导致请求失败。

2. Thymeleaf页面表单代码

<!-- 商品分类下拉框 -->
<div class="form-item">
    <label>商品分类</label>
    <select id="categorySelect" name="productCategoryId">
        <option value="">请选择分类</option>
        <option th:each="category : ${productCategoryList}"
                th:value="${category.id}"
                th:text="${category.categoryName}">
        </option>
    </select>
</div>

<!-- 商品下拉框 -->
<div class="form-item">
    <label>商品</label>
    <select id="productSelect" name="productId">
        <option value="">请先选择商品分类</option>
    </select>
</div>

确保Controller返回页面时已经携带productCategoryList参数,加载所有可选的商品分类。

3. 联动逻辑JS代码

以下是原生JS实现,无需引入额外依赖:

document.getElementById('categorySelect').addEventListener('change', function () {
    const selectCategoryId = this.value;
    const productSelect = document.getElementById('productSelect');
    // 先清空原有商品选项
    productSelect.innerHTML = '<option value="">请选择商品</option>';

    if (!selectCategoryId) return;

    // 请求后端接口获取商品列表
    fetch(`/common-api/list-product-by-category?categoryId=${selectCategoryId}`)
        .then(res => res.json())
        .then(productList => {
            productList.forEach(product => {
                const option = document.createElement('option');
                option.value = product.id;
                option.innerText = product.productName;
                productSelect.appendChild(option);
            })
        })
        .catch(err => console.log('商品列表加载失败:', err))
})

如果页面加载时分类有默认选中值,可在JS初始化时手动触发一次change事件,自动加载对应分类的商品。

内容的提问来源于stack exchange,提问作者Əziz Rəhimov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 10:36:04