How to access Spring MVC model object in javascript file? How to access Spring MVC model object in javascript file? spring spring

How to access Spring MVC model object in javascript file?


JavaScript is run on the client side. Your model 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.

Update:

A simple example

<%-- SomeJsp.jsp --%><script>var paramOne =<c:out value="${paramOne}"/></script>


Another solution could be using in JSP:<input type="hidden" id="jsonBom" value='${jsonBom}'/>

and getting the value in Javascript with jQuery:

var jsonBom = $('#jsonBom').val();


I recently faced the same need. So I tried Aurand's way but it seems the code is missing ${}. So the code inside SomeJsp.jsp <head></head>is:

<script>  var model=[];  model.paramOne="${model.paramOne}";  model.paramTwo="${model.paramTwo}";  model.paramThree="${model.paramThree}";</script>

Note that you can't asssign using var model = ${model} as it will assign a java object reference. So to access this in external JS:

$(document).ready(function() {   alert(model.paramOne);});