0

I have a controller which is passing the json object wrapped inside a model.

@RequestMapping("/template")
public String showTemplate(Model model) {       
    JSONObject obj = new JSONObject();
    obj.put("equipmentID", "30584D277D6D4568B17EBB8917D0CB15");
    model.addAttribute("template",obj);
    return "templates";
}

I would like to use these values in my javascript. I am not able to do that. However, I can see display these values in HTML.

<head>
<script>
    function test()
    {
    var temp = "${template}";
    alert(temp); // The values are not displayed here
    }
</script>

<body onload="test()">
    <span th:text="${template}"> </span> //I can display the values here        
<body>

I have also looked into this question How to get spring mvc controller model key value inside javascript? and tried both the options with or without quotes with no success.

I have also tried defining in HTML:

        <input type="hidden" id="templates" value='${template}'/>       

and using getElementById in my javascript with no success:

        var template = document.getElementById("templates");
1
  • I am struggling with the same problem bro... Have you solved this problem yet? Commented Oct 15, 2021 at 15:16

2 Answers 2

0

Using thymeleaf inlining you can use the below:

<script th:inline="javascript">
var message = [[${template}]];
alert(template);
</script>

There are additional ways to access server side variables depending on your use case refer to http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining for more information.

Sign up to request clarification or add additional context in comments.

Comments

0

Sometimes it has to do with the script's execution time. That is probably why you can display it on the body (meaning after page rendering) but not on the script.

So, what I would suggest is to have JS script as a separate file (e.g. test.js) and then include it in your HTML with the defer keyword (e.g. <script src="/js/test.js" defer></script>).

Using defer guarantees that the script is executed after page load (see How to make JavaScript execute after page load? for more details)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.