我希望以下表单使用 AJAX。因此,单击命令按钮后会显示评论,而无需重新加载页面。使用 Java Server Faces 2.0 需要更改哪些内容?
功能:此表单提供一个输入文本来定义主题。按下命令按钮后,将搜索有关该主题的评论。注释显示在数据表中(如果有)。否则会显示空。
<h:form id="myForm">
<h:outputLabel value="Topic:" for="topic" />
<h:inputText id="topic" value="#{commentManager.topic}" />
<h:commandButton value="read" action="#{commentManager.findByTopic}" />
<h:panelGroup rendered="#{empty commentManager.comments}">
<h:outputText value="Empty" />
</h:panelGroup>
<h:dataTable
id="comments"
value="#{commentManager.comments}"
var="comment"
rendered="#{not empty commentManager.comments}"
>
<h:column>
<h:outputText value="#{comment.content}"/>
</h:column>
</h:dataTable>
</h:form>
最佳答案
您需要告诉命令按钮使用 Ajax。就像嵌套 <f:ajax>
一样简单里面有标签。您需要通过execute="@form"
指示它提交整个表单。并渲染 ID 为 comments
的元素通过render="comments"
.
<h:commandButton value="read" action="#{commentManager.findByTopic}">
<f:ajax execute="@form" render="comments" />
</h:commandButton>
不要忘记确保您有 <h:head>
而不是<head>
在主模板中,以便自动包含必要的 JSF ajax JavaScript。
<h:head>
...
</h:head>
此外,ID 为 comments
的元素需要由 JSF 已经渲染到客户端,以便能够再次由 JavaScript/Ajax 更新(重新渲染)。所以最好是输入<h:dataTable>
在 <h:panelGroup>
使用该 ID。
<h:panelGroup id="comments">
<h:dataTable rendered="#{not empty commentManager.comments}">
...
</h:dataTable>
</h:panelGroup>
另请参阅:
关于ajax - 使用 AJAX 的 JSF 表单发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6472016/