0

目标是拥有一个h:commandButton,一旦我单击它,使用 AJAX 它将显示数据表“listaActores”(最初不显示它)。

我怎么能这样做?我已经在寻找解决方案,但我只找到了如何在表格出现时重新渲染表格。我当前的代码什么都不做就显示了表格,点击按钮什么也不做。

<h:form>
    <h:commandButton id="submit" value="Submit">
        <f:ajax event="click" execute="@this" render="listaActores" />
    </h:commandButton>
    <h:dataTable id="listaActores" border="1"
        value="#{peliculasEditarBean.listaActores}" var="actor">
        <h:column>
            <f:facet name="header">NOMBRE</f:facet>
            #{actor.nombre}
        </h:column>
        <h:column>
            <f:facet name="header">APELLIDO</f:facet>
            #{actor.apellido}
        </h:column>
    </h:dataTable>
</h:form>
4

1 回答 1

1

Your question is somewhat incomplete, but I'll answear anyway. Two things:

  1. You're not saying how the table is "initially not showing". If there is some rendered on it, than you need to know that you must render a parent of the table. You can render only things that exist in rendered HTML. See for example this answer.

  2. If you'll put action in the button you'll see that the AJAX won't work. You need to change event to action or delete this attribute to use a default.

I preperend simple working example (BTW. Welcome on Stackoverflow :-) If you want get help faster Minimal, Reproducible Example should be your's part of a question :-)):

(XHTML, added action to commandButton and remove event in f:ajax)

<h:form>
    <h:commandButton id="submit" value="Submit"
        action="#{peliculasEditarBean.initialize}">
        <f:ajax execute="@this" render="listaActores" />
    </h:commandButton>
    <h:dataTable id="listaActores" border="1"
        value="#{peliculasEditarBean.listaActores}" var="actor">
        <h:column>
            <f:facet name="header">NOMBRE</f:facet>
                #{actor.nombre}
            </h:column>
        <h:column>
            <f:facet name="header">APELLIDO</f:facet>
                #{actor.apellido}
            </h:column>
    </h:dataTable>
</h:form>

(and bean)

@ManagedBean
@ViewScoped
public class PeliculasEditarBean implements Serializable {

    private List<Actor> listaActores = null;

    public List<Actor> getListaActores() {
        return listaActores;
    }

    public void initialize() {
        listaActores = new ArrayList<>(3);
        listaActores.add(new Actor("foo", "bar"));
        listaActores.add(new Actor("foo", "foo"));
        listaActores.add(new Actor("bar", "bar"));
    }
    
    public class Actor {
        private final String nombre;
        private final String apellido;

        Actor(String nombre, String apellido) {
            this.nombre = nombre;
            this.apellido = apellido;
        }

        public String getApellido() {
            return apellido;
        }

        public String getNombre() {
            return nombre;
        }
    }
}
于 2020-12-16T12:46:29.143 回答