如何通过 AJAX 单击命令按钮在 JSF 中呈现数据表

How to render a datatable in JSF with AJAX clicking a commandButton

objective 是有一个 h:commandButton,一旦我点击它,使用 AJAX 它将显示数据 table “listaActores”(最初不显示它)。

我该怎么做?我已经搜索了一个解决方案,但我只找到了如何重新呈现 table once 存在。我当前的代码显示 table 什么都不做,点击按钮也没有做任何事情。

<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>

你的问题有点不完整,不过我还是会回答的。两件事:

  1. 您不是在说 table 是如何“最初不显示”的。如果上面有一些 rendered,那么您需要知道必须渲染 table 的父级。您只能渲染存在于 rendered HTML 中的东西。例如,参见 answer.

  2. 如果您将 action 放在按钮中,您会发现 AJAX 不起作用。您需要将事件更改为 action 或删除此属性以使用默认值。

我预先添加了简单的工作示例(顺便说一句。欢迎使用 Whosebug :-) 如果您想更快地获得帮助 Minimal, Reproducible Example 应该是您的问题的一部分 :-)):

(XHTML,将 action 添加到 commandButton 并在 f:ajax 中删除 event)

<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>

(和豆)

@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;
        }
    }
}