javascript - 未捕获的 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”的语法有问题。
解决方案
在这个例子中我注意到了两个潜在的问题:
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) 点,这可能无法让您一直获得完整的解决方案,但它应该会有所帮助。
推荐阅读
- sql - 使用带有多个变量的 CLR/C++ 时,如何防止我的 SQL 语句被 SQL 注入?
- sharepoint-online - 弹出窗口以在 Sharepoint 中输入上传文件的必填列字段
- azure - Ms 团队 Mobile 和 Bot Framework:发送图像
- css - 当父DIV宽度按百分比设置时防止文本溢出DIV
- php - 使用关系表从数据库中获取记录时出现问题
- python - Python - Instaloader ProfileNotExistsException
- android - 处理 Imageview 和指南
- google-cloud-dataflow - 数据流 UDF 的更新延迟
- r - 使用 rvest、xml2 和选择器小工具进行网络抓取会导致 xml_missing
- npgsql - Teiid:Npgsql 不支持弃用的浮点日期/时间格式