[英]Uncaught SyntaxError: Invalid or unexpected token in thymeleaf template
I have been trying to pass a list of object which contains products details through on button click.我一直在尝试通过单击按钮传递包含产品详细信息的 object 列表。 But I get "Uncaught SyntaxError: Invalid or unexpected token" for the list of object.
但我收到 object 列表的“未捕获语法错误:无效或意外令牌”。
<button type="button" th:onclick="'javascript:addProductFields(' + ${status.index} + ', ' + ${status1.index} + ',' + ${dailySaleHistoryDto.productList} +')'" class="btn btn-info"> +</button>
My guess is there is something wrong with the syntax for passing reference "dailySaleHistoryDto.productList".我的猜测是传递参考“dailySaleHistoryDto.productList”的语法有问题。
There are two potential problems which I notice in this example:在这个例子中我注意到了两个潜在的问题:
1) dailySaleHistoryDto.productList 1) dailySaleHistoryDto.productList
As you mention in your question, this may be a problem (or it may not be).正如您在问题中提到的,这可能是一个问题(也可能不是)。 If the productList is actually a Java
List
object, then you may not get the results you expect - Thymeleaf will convert this to a string in your template.如果 productList 实际上是 Java
List
object,那么您可能不会得到您期望的结果 - Thymeleaf 会将其转换为模板中的字符串。 If the object is a list of strings, then you will get something that looks like a string representation of an array:如果 object 是一个字符串列表,那么你会得到看起来像数组的字符串表示形式的东西:
[item1, item2, ...]
This may, or may not, be a problem - it depends on what you need to do with the data.这可能是也可能不是问题 - 这取决于您需要对数据做什么。 For example, you can convert it back from a string into an array in JavaScript.
例如,您可以将其从字符串转换回 JavaScript 中的数组。
2) The "onclick" JavaScript 2)“点击”JavaScript
You will need to use Thymeleaf's [[...]]
inlining notation for embedding Thymeleaf variables into JavaScript.您将需要使用 Thymeleaf 的
[[...]]
内联符号将 Thymeleaf 变量嵌入到 JavaScript 中。 I would recommend moving the JavaScript into its own section - for example, in your document's header.我建议将 JavaScript 移到其自己的部分中 - 例如,在文档的 header 中。 So, something like this:
所以,像这样:
<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>
Then, you can simplify your button to this:然后,您可以将按钮简化为:
<button type="button" onclick="addProductFields();" class="btn btn-info"> +</button>
Note that you no longer need to use th:onclick
- just onclick
.请注意,您不再需要使用
th:onclick
- 只需onclick
。 You have moved all the variables to a separate script (in this example).您已将所有变量移至单独的脚本(在此示例中)。
This may not get you all the way to a complete solution, because of point (1), but it should help.由于第 (1) 点,这可能无法让您一直获得完整的解决方案,但它应该会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.