1

I have a controller where a JSONObject is passed as parameter. I would like to work with the object "all" in javascript (client side) not in the server side (JSP) so I don't want to get the object with JSP tags.

 @RequestMapping(value = { "/dfi/rca" }, method = RequestMethod.GET)
    public String getRcaResult(Model model, String flight_id) {
        ...
        JSONObject all = new JSONObject ();
        ...
        model.addAttribute("all",all);          
        return "dfi/rca";
    }

I have a JSP file that import a Javasript file where I use the attribute all but I don't know how to access to it. If I use this code in the JSP file it works properly:

<script type="text/javascript">
     var all= "${all}";
</script>

But if I try the same importing a Javascript file in the JSP, it doesn't get anything:

<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/all.js"></script>

In all.js:

var rcaresults = JSON.parse('${all}');

Are there any way to read the Spring model attributes in a Javascript file?

Thanks in advance.

2 Answers 2

1

JavaScript is run on the client side. Your model model.addAttribute("all",all); does not exist on the client side, it only exists on the server side while you are rendering your .jsp.

If you want data from the model to be available to client side code (ie. javascript), you will need to store it somewhere in the rendered page. For example, you can use your Jsp to write JavaScript assigning your model to JavaScript variables. e.g <script>var paramOne =<c:out value="${all}"/></script>

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

1 Comment

Thanks, finally I got the data in the JSP (server) then called a function defined in the javascript file (client) <script type="text/javascript">var all = '${all}'; graphsData(all); </script>
1

when you use src, your browser (and not your backend) will try to fetch the javascript file from

"${pageContext.request.contextPath}/resources/js/all.js"

so the file is not processed by the server as a ModelView.

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.