【问题标题】:Uncaught SyntaxError: Invalid or unexpected token in thymeleaf template未捕获的 SyntaxError:百里香模板中的无效或意外标记
【发布时间】:2020-07-18 01:38:29
【问题描述】:

我一直在尝试通过单击按钮传递包含产品详细信息的对象列表。但是我得到对象列表的“未捕获的语法错误:无效或意外的令牌”。

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

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

【问题讨论】:

    标签: javascript spring-boot thymeleaf


    【解决方案1】:

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

    1) dailySaleHistoryDto.productList

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

    [item1, item2, ...]
    

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

    2) “onclick” JavaScript

    您需要使用 Thymeleaf 的 [[...]] inlining 表示法将 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 - 只需 onclick。您已将所有变量移至单独的脚本(在本例中)。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      • 1970-01-01
      • 2020-10-13
      相关资源
      最近更新 更多