I have a jQuery library that wants you to pass it a JavaScript object as an option. For example, this works:
//Hardcoded JavaScript object
var myData = { "A" : "1", "B" : "2", "C" : "3" };
//Call to jQuery with object as an option
$("#mySelectorId").myJqueryFunction({values: myData});
I need the myData
object to not be hardwired like that.
I can easy get the "A to 1, B to 2, C to 3" structure in my Java code, put it in a Map
(or some other object), and add it to the request via request.setAttribute("myData", myMap);
. I am just not sure how to convert the Map
(etc) into the needed JavaScript object. Here is what I have tried.
//Java
Map<String, String> myMap = new TreeMap<String, String>();
map.put("A", "1");
map.put("B", "2");
map.put("C", "3");
request.setAttribute("myMap", myMap);
//JSP
<c:set var="myData" value="{" />
<c:forEach var="mapEntry" items="${myMap}" varStatus="counter">
<c:set var="myData" value="${myData}'${mapEntry.key}' : '${mapEntry.value}'" />
<c:if test="${counter.count < fn:length(myMap)}">
<c:set var="myData" value="${myData}, " />
</c:if>
</c:forEach>
<c:set var="myData" value="${myData}}" />
<script>
var myData = '${myData}';
$("#mySelectorId").myJqueryFunction({values: myData});
</script>
This works until the myJqueryFunction
reaches a point where it tries to do something like this:
var i = values[code];
Essentially, it is trying to reference a particular variable on the object (e.g. trying to get the value of "B", which is 2). Note that code
is a function parameter that holds the A/B/C value.
I have tried messing around with including or not including the quotes around ${mapEntry.key}
and things like that, but nothing seems to work.
Does anyone know how to get this working?