Reputation: 3019
I need to pass an array of strings from the backing bean to the JSP. I can use a h:dataTable and display each string as a h:column entry with no problem. But I need to display this list of strings in an alert box instead of embedding it into the JSP itself. How would I pass the list to a JavaScript function and iterate over it? I then want to append each string to a variable and show it.
Here is the original data table:
<h:dataTable id="scriptCommandTable" value="#{viewScriptRules.scriptCommands}" var="scriptCommand" columnClasses="scriptCommandSequence,scriptCommandRule" rendered="#{viewScriptRules.scriptCommandsSize > 0}">
<h:column>
<h:outputText value="#{scriptCommand.sequence}."/>
</h:column>
<h:column>
<h:outputText value="#{scriptCommand.rule}" escape="false"/>
</h:column>
</h:dataTable>
Upvotes: 0
Views: 4563
Reputation: 1108722
Just print it as an array of JS objects.
<script>
var commands = [
<c:forEach items="#{viewScriptRules.scriptCommands}" var="command" varStatus="loop">
{
'sequence': '<h:outputText value="#{command.sequence}"/>',
'rule': '<h:outputText value="#{command.rule}" escape="false" />'
}
<h:outputText value="#{!loop.last ? ',' : ''}" />
</c:forEach>
];
for (var i = 0; i < commands.length; i++) {
var command = commands[i];
alert(command.sequence + "," + command.rule);
}
</script>
Much better, however, is to provide it as a webservice which returns a JSON string. In a JavaScript library like jQuery you can seamlessly access them.
<script>
$.getJSON('someurl', function(data) {
$.each(data, function(index, command) {
alert(command.sequence + "," + command.rule);
});
});
</script>
You can use a plain vanilla Servlet for this (example here) or a JAX-RS.
Upvotes: 3
Reputation: 14581
Include another property in your backing bean that is a string composed of the concatated items from the list. Property can be set when the list is populated. I know that is not java script.
Upvotes: 0