我正在开发一个JSF应用程序,希望使用Ajax定时刷新组件,类似于Facebook的通知区域行为。我该怎么做?
我正在开发一个JSF应用程序,希望使用Ajax定时刷新组件,类似于Facebook的通知区域行为。我该怎么做?
你需要使用轮询(Poll)
轮询组件能够在指定的时间间隔内发起 ajax 调用。
例如 Primefaces Poll 组件。
<h:form id="form">
<h:outputText id="txt_count" value="#{counterBean.count}" />
<p:poll interval="3" listener="#{counterBean.increment}" update="txt_count" />
</h:form>
纯JSF方法是使用JS定时器,周期性调用document.getElementById('someFormId:idOfButton').click();
或jQuery $("#someFormId\\:idOfButton").click();
按钮应如下所示:
<h:commandButton id="idOfButton">
<f:ajax render="txt_count"></f:ajax>
</h:commandButton>
类似这样的东西
setInterval(function(){$("idOfButton").click()},3000);
了解更多关于计时器的内容,请参考JavaScript Timing Events
在 RichFaces 中也有一个轮询组件。他们提供了一个很好的例子,可以参考这里
<a4j:region>
<h:form>
<a4j:poll id="poll" interval="1000" enabled="#{userBean.pollEnabled}" reRender="poll,grid"/>
</h:form>
</a4j:region>
<h:form>
<h:panelGrid columns="2" width="80%" id="grid">
<h:panelGrid columns="1">
<h:outputText value="Polling Inactive" rendered="#{not userBean.pollEnabled}" />
<h:outputText value="Polling Active" rendered="#{userBean.pollEnabled}" />
<a4j:commandButton style="width:120px" id="control" value="#{userBean.pollEnabled?'Stop':'Start'} Polling" reRender="poll, grid">
<a4j:actionparam name="polling" value="#{!userBean.pollEnabled}" assignTo="#{userBean.pollEnabled}"/>
</a4j:commandButton>
</h:panelGrid>
<h:outputText id="serverDate" style="font-size:16px" value="Server Date: #{userBean.date}"/>
</h:panelGrid>
</h:form>