在引入的js文件中读取后端model中的值(使用thymeleaf)

本文介绍了如何在Spring MVC控制器中操作数据,并以JSON格式传递给前端。详细展示了如何使用`@RequestMapping`处理'/index'请求,将分层次的Category数据存储到Model中,以便在页面上动态显示。
摘要由CSDN通过智能技术生成

结构如下:

分三步

1. controller中添加数据

    @RequestMapping({"/", "/index"})
    public String indexPage(Model model) {
        List<CategoryEntity> list = categoryService.listWithTree();
        List<CategoryEntity> parents = new ArrayList<>();
        Map<String, List<CategoryEntity>> children = list.stream().peek(cat -> {
            CategoryEntity parent = new CategoryEntity();
            parent.setId(cat.getId());
            parent.setName(cat.getName());
            parents.add(parent);
        }).collect(Collectors.toMap(k -> k.getId().toString(), v -> v.getChildren()));
        model.addAttribute("parents", parents);
        model.addAttribute("children", JSON.toJSONString(children));
        return "index";
    }

2. 页面使用input保存传来的数据

<div class="header_main_left">
    <!-- 储存数据 -->
   <input id="categoryList" hidden th:value="${children}">
   <ul>
      <li th:each="category: ${parents}">
         <a href="#" class="header_main_left_a" th:attr="ctg-data=${category.id}"><b th:text="${category.name}"></b></a>
      </li>
   </ul>
</div>

3. js文件中通过id获取这个input的值

$(function () {
    let children = JSON.parse($('#categoryList').val())
    console.log(children)
    //.....
}

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

欧内的手好汗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值