pass list to js, thymeleaf,springboot

7.4k Views Asked by At

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?

1

There are 1 best solutions below

2
On

Instead 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.