Hafiz Athar Hafiz Athar - 17 days ago 6
HTML Question

How to get value from spring controller class in javascript?

I have a controller class in spring. I am passing values such as a simple string or a hashmap. I know how to get values in thymeleaf. I want to get values on my html page in pure javascript, no thymeleaf. My controller class :

String s="RUSSIA";
@RequestMapping(value = "/", method = RequestMethod.GET)
public String Country( Model model) {
model.addAttribute("country", s);
return "index";
}


Now I want to get this string in javascript variable. I am using HTML not JSP.

Answer

You could do something like this:

<script th:inline="javascript">
/*<![CDATA[*/

    var country = [[${country}]];
    console.log(country);

/*]]>*/
</script>

If you want to run your html offline you can do this, and the JS variable will be always the fixed value of Russia

var country = /*[[${country}]]*/ 'Russia';
Comments