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

Thymeleaf th:onclick传递List属性至JS函数失败求助

解决Thymeleaf传递List到JavaScript函数的标签消失问题

问题背景

在SpringBoot中通过attributes.addFlashAttribute("mylist", mylist)传递List类型属性,使用Thymeleaf尝试将其传给JavaScript函数时,<th>标签消失,两种写法均失败:

  1. 直接在th:onclick中嵌入List:
<th scope="col">
    <i class="fas fa-plus" type="button" 
       th:onclick="|myfunction('staticValue', [[${mylist}]]);|">
    </i>
</th>
  1. 通过data属性传递:
<i class="fas fa-plus" type="button" 
   th:data-materialTypeSetDes="${mylist}"
   onclick="function('staticValue', this.getAttribute('data-materialTypeSetDes'));"></i>

使用Thymeleaf 3.0.15版本,未使用Thymeleaf属性时JavaScript功能正常。

解决方案

核心问题是直接传递Java List会输出其toString()结果(如[com.example.Entity@xxxx, ...]),这是JS无法识别的无效语法,导致Thymeleaf解析错误,标签渲染失败。需将List序列化为JSON字符串后传递:

方案1:后端序列化List为JSON

在后端将List转为JSON字符串再存入Flash属性:

import com.fasterxml.jackson.databind.ObjectMapper;
// ...
ObjectMapper objectMapper = new ObjectMapper();
String mylistJson = objectMapper.writeValueAsString(mylist);
attributes.addFlashAttribute("mylistJson", mylistJson);

前端通过data属性传递并解析:

<th scope="col">
    <i class="fas fa-plus" type="button" 
       th:data-mylist="${mylistJson}"
       onclick="myfunction('staticValue', JSON.parse(this.getAttribute('data-mylist')));">
    </i>
</th>

或直接在th:onclick中使用(需转义JS特殊字符):

<th scope="col">
    <i class="fas fa-plus" type="button" 
       th:onclick="|myfunction('staticValue', ${#strings.escapeJavaScript(mylistJson)});|">
    </i>
</th>

方案2:Thymeleaf内置工具序列化

若项目已引入Jackson依赖,可直接用Thymeleaf的#objectMapper工具类在前端序列化:

<th scope="col">
    <i class="fas fa-plus" type="button" 
       th:data-mylist="${#objectMapper.writeValueAsString(mylist)}"
       onclick="myfunction('staticValue', JSON.parse(this.getAttribute('data-mylist')));">
    </i>
</th>

注意:确保List中的对象有正确的Getter方法,无循环引用,否则会序列化失败。

失败原因分析

  • 直接输出${mylist}得到的是Java对象的字符串表示,不是JS可识别的数组/JSON格式,导致生成的HTML中JS语法错误,Thymeleaf解析时跳过了整个<th>标签的渲染,所以标签消失。
  • data属性存的List字符串包含JS无法解析的字符(如@),无法直接转为可用的JS数组。

内容的提问来源于stack exchange,提问作者Discipulos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:35:24