"显示更多“<h: 命令按钮>使用ajax

"show more" <h:commandButton> with ajax

本文关键字:命令 按钮 使用 ajax gt lt 显示 quot      更新时间:2024-02-05

我在MyFaces2.0的实现中使用JSF。在我的web应用程序中,我希望有一个带有"显示更多"按钮的页面。用户获取页面时,只有按钮和带有一些信息的隐藏表单(例如带有标签)。当用户点击这个按钮时,他会在显示标签的同一页面上看到。当他再次点击时,标签应该隐藏起来。

myPage.xhtml:

<?xml version='1.0' encoding='UTF-8' ?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<h:body>
    <h:form>
       <h:commandButton value="show more" action="#{bean.showOrHide}">
           <f:ajax render=":formWithLabel"/>
       </h:commandButton>
    </h:form>  
    <hr/>
    <h:form id="formWithLabel" rendered="#{bean.show}">
       <h:outputLabel value="More information"/>
    </h:form>
</h:body>

Bean.java:

@ManagedBean
@ViewScoped
public class Bean {
  private boolean show;
  //getters, setters
  public void showOrHide(){
    show = !show;
  }
}

此代码似乎不起作用。怎么了?

实际上,这种方法是行不通的。

<f:ajax render=":formWithLabel"/>的工作原理如下:

  1. JavaScript发送一个ajax请求
  2. JSF在更新后的HTML中返回一个带有<update id="formWithLabel">的ajax响应
  3. JavaScript使用document.getElementById("formWithLabel")来查找元素,以便将其内部HTML内容替换为ajax响应中的内容

然而,由于<h:form id="formWithLabel" rendered="#{bean.show}">从来没有被呈现过,JavaScript在HTML文档中找不到任何东西来用ajax响应中的内容替换内部HTML内容,因此默默地失败了。

您需要将其封装在另一个JSF组件中,该组件总是呈现为HTML输出,这样JavaScript就可以在需要基于ajax响应更新HTML文档时找到它。

<h:form>
   <h:commandButton value="show more" action="#{bean.showOrHide}">
       <f:ajax render=":groupWithLabel"/>
   </h:commandButton>
</h:form>  
<h:panelGroup id="groupWithLabel">
    <h:form id="formWithLabel" rendered="#{bean.show}">
       <h:outputLabel value="More information"/>
    </h:form>
</h:panelGroup>

另请参阅:

  • Ajax呈现本身有条件呈现的内容

与具体问题无关当您打算在此表单上调用操作时,可能会偶然发现一个新问题。您可能希望将<h:panelGroup><h:form>交换。

另请参阅:

  • Ajax呈现包含另一个表单的内容