首页 > 解决方案 > 未捕获的 SyntaxError:百里香模板中的无效或意外标记

问题描述

我一直在尝试通过单击按钮传递包含产品详细信息的对象列表。但是我得到对象列表的“Uncaught SyntaxError: Invalid or unexpected token”。

<button type="button" th:onclick="'javascript:addProductFields(' + ${status.index} + ', ' + ${status1.index} + ',' + ${dailySaleHistoryDto.productList} +')'" class="btn btn-info"> +</button>

我的猜测是传递参考“dailySaleHistoryDto.productList”的语法有问题。

标签: javascriptspring-bootthymeleaf

解决方案


在这个例子中我注意到了两个潜在的问题:

1) dailySaleHistoryDto.productList

正如您在问题中提到的,这可能是一个问题(也可能不是)。如果 productList 实际上是一个 JavaList对象,那么您可能不会得到您期望的结果 - Thymeleaf 会将其转换为模板中的字符串。如果对象是一个字符串列表,那么你会得到一个看起来像数组的字符串表示形式的东西:

[item1, item2, ...]

这可能是也可能不是问题 - 这取决于您需要对数据做什么。例如,您可以将其从字符串转换回 JavaScript 中的数组。

2) “onclick” JavaScript

您需要使用 Thymeleaf 的[[...]] 内联符号将 Thymeleaf 变量嵌入 JavaScript。我建议将 JavaScript 移到它自己的部分 - 例如,在文档的标题中。所以,像这样:

<head>
...
  <script th:inline="javascript">
    function addProductFields() {
      var status = [[${status.index}]];
      var status1 = [[${status1.index}]];
      var dailySaleHistoryDto = [[${dailySaleHistoryDto.productList}]];
      // show that it worked - print the values to the browser console:
      console.log(status);
      console.log(status1);
      console.log(dailySaleHistoryDto);
      // whatever logic you need goes here...
    }
  </script>
</head>

然后,您可以将按钮简化为:

<button type="button" onclick="addProductFields();" class="btn btn-info"> +</button>

请注意,您不再需要使用th:onclick-just onclick。您已将所有变量移至单独的脚本(在此示例中)。

由于第 (1) 点,这可能无法让您一直获得完整的解决方案,但它应该会有所帮助。


推荐阅读