admin管理员组文章数量:1430748
I want to pass a List from a controller to a javascript file and iterate the it in the js file. But I only got "undefined" in the js.
I use Thymeleaf template and my js file is separated from my html.
//controller
List<Bean> list = new ArrayList<Bean>();
model.addAttribute("list", list);
//html
<input id="list" type="hidden" th:value="${list}"/>
//javascript
var list=$('#list').val();
console.log("list: "+ list);
//[Bean(month=201805, date=2018-05-02),Bean(month=201804, date=2018-05-03)], which is correct
for(var i in list) {
console.log("date: "+ list[i].date); // I got undefined
console.log("month: "+ list[i].month); // I got undefined,too
}
I expect to get the value of month and date, does anyone have any idea?
I want to pass a List from a controller to a javascript file and iterate the it in the js file. But I only got "undefined" in the js.
I use Thymeleaf template and my js file is separated from my html.
//controller
List<Bean> list = new ArrayList<Bean>();
model.addAttribute("list", list);
//html
<input id="list" type="hidden" th:value="${list}"/>
//javascript
var list=$('#list').val();
console.log("list: "+ list);
//[Bean(month=201805, date=2018-05-02),Bean(month=201804, date=2018-05-03)], which is correct
for(var i in list) {
console.log("date: "+ list[i].date); // I got undefined
console.log("month: "+ list[i].month); // I got undefined,too
}
I expect to get the value of month and date, does anyone have any idea?
Share Improve this question asked May 23, 2018 at 11:39 VikkiVikki 2,0352 gold badges20 silver badges24 bronze badges1 Answer
Reset to default 3Instead of putting the list into an html element, just put it directly into the Javascript. Like this:
<script th:inline="javascript">
var list = /*[[${list}]]*/ [];
</script>
<script src="/your_other_javascript_file.js"></script>
The reason your loop isn't working is that $('#list').val();
is not an array, it is a string. Looping over a string won't do what you expect.
本文标签: javascriptpass list to jsThymeleafspringbootStack Overflow
版权声明:本文标题:javascript - pass list to js, thymeleaf,springboot - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745545335a2662677.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论