Using Spring variable in javascript

I am trying to use Spring variable in javascript:

Map<String, List<String>> states; 

and i found some info here

so i tried:

 <script th:inline="javascript"> /*<![CDATA[*/ var xxx = ${states}; console.log(xxx); /*]]>*/ </script> 

In my browser source tab, I have something like:

 var xxx = {STATE1=[a, b, c, d]}; console.log(xxx); 

and error: Uncaught SyntaxError: Invalid shorthand property initializer .

I also tried: var xxx = /*[[${states}]]*/ 'foo'; , and if I type console.log(xxx) , I got 'foo' .

+5
source share
2 answers

I solved the problem using your comments:

1) There was no single quote:

 <script th:inline="javascript"> /*<![CDATA[*/ var xxx = '${states}'; console.log(xxx); /*]]>*/ </script> 

2) The object should be analyzed as follows:

  var hashmap = $.parseJSON(xxx); 

3) And before I need to serialize my object (this is not an ajax call, so I need to serialize it manually):

 Map<String, List<String>> states... model.addAttribute("states", new ObjectMapper().writeValueAsString(states)); 

So now I can read my object:

 var myList = hashmap['STATE1']; console.log(myList ) 

will print [a, b, c, d] and I can execute the loop:

 for(i in myList ){ console.log(myList[i]); } 
0
source

This error is due to the fact that {STATE1=[a, b, c, d]} is an invalid Javascript object.

The explanation is very trivial: you see the server-side rendering product (you use Thymeleaf as fat, as I can suggest with the th:inline tag). Thus, on the server, your map object will be displayed as the string {STATE1=[a, b, c, d]} . On your client (browser) you get a page with this line, nothing more. There is already no Java object. Just a line. And this line is invalid object initialization in Javascript.

Therefore, you simply cannot use the card in this way. You cannot parse this with JSON.parse because it is invalid JSON (instead of = used : .

Hope this helps!

PS If you try to replace = with : in Javascript, it will work differently than you expect: the array [a, b, c, d] will be considered as an array of variables with names a , b , c and d , so you will have to use it in. '' But I suggest discarding this idea and rethinking the approach. This is not how it should be used.

+2
source

Source: https://habr.com/ru/post/1271318/


All Articles