JSF,如何使用Ajax定时刷新组件?

17

我正在开发一个JSF应用程序,希望使用Ajax定时刷新组件,类似于Facebook的通知区域行为。我该怎么做?


5
将来如果您提出问题,请明确提及使用的组件库,例如PrimeFaces。如果您没有提及任何内容,则默认为标准JSF。 - BalusC
2个回答

34

你需要使用轮询(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>

展示链接Primefaces Ajax投票

纯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


2
根据OP的问题历史记录,他正在使用PrimeFaces,所以这非常合适。 - BalusC

5

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接