What is the best way to access a java Map from javascript while using Spring MVC?
I'm building a webpage where depending on the values you chose from a checkbox, a dynamic text will appear in another div with further details regarding that option by using getElementById("element").innerHTML=${var}.
I'm using Maps to populate the checkbox options, and it does works fine in JSPs but simply won't work in javascript scriptlets or external .js files. It just understands it as a string, not as a Map or Array.
The following code is what I've got so far:
Properties file:
checkBoxItems={'0':'The Value'}
myMapObject={'0','Map Stuff'}
In Controller java file:
@Controller
@RequestMapping(value = "/example")
public Class ExampleController
{
@Value("#{${checkBoxItems}}")
Map<String, String> checkBoxOptions;
@Value("#{${myMapObject}}")
Map<String, String> myMapObject;
@RequestMapping(value = "/newExample", method = RequestMethod.GET)
public String Hello(Model model)
{
model.addAttribute("checkBoxOptions", checkBoxOptions);
model.addAttribute("myMapObject", myMapObject);
return "view";
}
}
in JSP: (I've simplified to show what I aim to achieve)
<form:select class="custom-select" id="metodologia" path="metodologia"
onchange="FillWithComplement('${myMapObject}')">
<form:option value="-">Select an Option</form:option>
<form:options items="${checkboxOptions}"/>
</form:select>
In the first javascript trial:
<script>
function FillWithComplement(MapObject)
{
document.getElementById("div").innerHTML = MapObject;
}
</script>
the output is:
{0=Map Stuff}
And it also doesn't work if I do:
<script>
function FillWithComplement(MapObject)
{
var newMap = new Map(MapObject);
document.getElementById("div").innerHTML = newMap;
}
</script>
And I am aware I might not have enough javascript knowledge do handle this correcty. Thanks.
EDIT:
As proposed by Yan Khonski, passing data as JSON by asynchronous request (ajax) worked with minor changes.
- dataType: 'json' returns a JSON object, so it is needless to implement a JSON parsing method.
The final code:
var globalMetodologiaComplemento;
$(document).ready(function () {
$.ajax({
type: 'GET',
url: '/gla/getMet',
dataType: 'json',
success: function (data) {
globalMetodologiaComplemento = data;
console.log(globalMetodologiaComplemento[0]);
}
});
});
(...)