1

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?

Vikki
  • 1,897
  • 1
  • 17
  • 24

1 Answers1

3

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.

Metroids
  • 18,999
  • 4
  • 41
  • 52
  • That's right. But I want to loop the list in an independent javascript file (namely, src="/your_other_javascript_file.js"), where I will draw a chart with the data in the list. I don't prefer drawing it in the html – Vikki May 24 '18 at 05:47
  • You're not drawing it in the the html. You're drawing it in `your_other_javascript_file.js` which is dependent on having a variable "list" already defined before it's loaded. If you really don't want to do that, then you're going to have to set up a new TemplateResolver with `resolver.setTemplateMode(TemplateMode.JAVASCRIPT);` and then make a new controller that returns your javascript file. Then you can use the model to pass your list directly into the javascript. – Metroids May 24 '18 at 14:37