For the past 24 hours I’ve been trying to pass objects from Java controllers to JSPs and use these objects in JavaScript code but in the JSPs these objects are converted to strings. For example if I have a list of locations passed to the view using
I cannot assign this list of locations to a JavaScript variable. When I do this,
var locations = "${locations}"
All this does is assign a string version of the list of locations which is just concatenated values of Location.getDisplayString(). As a result I can’t use this in JavaScript loops and I can’t even call properties on the objects.
When I do this
var locations = ${locations}
This doesn’t work. It gives a JavaScript error in the browser.
Uncaught SyntaxError: Unexpected identifier
How do I receive objects passed to the model in controllers as objects in views rather than strings?
JSON.parse("${locations}")
doesn’t work either. I get the error
VM2727:1 Uncaught SyntaxError: Unexpected token C in JSON at position 1
at JSON.parse ()
at HTMLDocument. (patientDashboard.form?patientId=6167&phrase=john:1716)
at Function.ready (jquery.min.js?v=1.9.11:26)
at HTMLDocument.L
Yes, If you assign the variable like that in JS, then it will be converted to a string (actually it doesn’t mean JSON String). And you can’t convert that to JSON since it does not contain the actual JSON format.
So the only way is creating a JSON in the controller and convert to JSON string object, and pass that string object through the JS. Then you can convert that string to JSON in the JS file since it’s an actual JSON string.
So you should try something like this in your controller,
SimpleObject obj = new SimpleObject();
for(Location loc : Context.getLocationService().getAllLocations()) {
SimpleObject locObj = new SimpleObject();
locObj.put("name", loc.getName());
locObj.put("uuid", loc.getUuid());
obj.put("location", locObj);
}
model.put("locations", mapper.writeValueAsString(obj));
Then in your JSP assign this stringObject to the JS variable,
var locationsMapping = "${locations}"
So then you can simply get the locationsMapping in your JS file, then you can use the foreach to get each object. if you are using angular then it should be like this following,
I just checked and seems SimpleObject is coming from the REST module. That will mean I’d have to declare a dependency to the REST module. That’s not an option for me. The implementation refused to add a new dependency just to make small fix.