简体   繁体   中英

How to iterate over a backing bean list of strings in JavaScript

I need to pass an array of strings from the backing bean to the JSP. I can use ah:dataTable and display each string as ah: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>

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM