Reputation: 10254
We normally do something like this JSTL on the jsp....but I now need to set data in the javascript using JSON. How would I do something like this in Javascript/JSON
Basically loop over a bean and pull out its parameters:
<c:forEach var="field" items="${detFields}">
${field.groupName}
${field.breakoutAllowed}
</c:forEach>
so I can put it inside something like this:
"data": [{
"value": "${field.groupName}"
}, {
"value": "${field.breakoutAllowed}"
}]
Upvotes: 0
Views: 1152
Reputation: 3825
Hope this code works well and is liked by you. I consider writing scriptlet into JS a kinda weird practice so just suggested another way of approaching it. Please comment if necessary.
$(document).ready(function(){
var k=$('#data').val();
//Convert the value into the required array. Since writing it is JavaScript directly is not a daily practice.
})
<input type="hidden" id="data" value=
<c:forEach var="field" items="${detFields}" varStatus="status">
{
"name":"${field.groupName}",
"breakoutAllowed":"${field.breakoutAllowed}"
}
<c:if test="${not status.last}">,</c:if>
</c:forEach>
/>
Upvotes: 1
Reputation: 5086
It looks like the JSON structure you're looking for is an array of objects, each with two properties: name
and breakoutAllowed
. JavaScript to assign this data to a variable could be output like this from a JSP file. (Within a <script>
block or equivalent, of course.)
var output = [
<c:forEach var="field" items="${detFields}" varStatus="status">
{
"name":"${field.groupName}",
"breakoutAllowed":"${field.breakoutAllowed}"
}
<c:if test="${not status.last}">,</c:if>
</c:forEach>
]
Upvotes: 1