如何以1秒的间隔对组件进行Ajax更新? [英] How do I ajax-update a component at an interval of 1 second?

查看:87
本文介绍了如何以1秒的间隔对组件进行Ajax更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在戴尔的一次采访中有人问我这个问题.

I was asked this question in an interview at Dell.

new Date()为您提供一个使用当前日期/时间初始化的Date对象.

new Date() gives you a Date object initialized with the current date / time.

让我们假设屏幕的右上角显示了当前时间,并且已经这样做了.

Let suppose the right top corner of my screen shows the present time, and one has done like this.

<h:outputText value="#{bean.presentDateTime}" />

将其修改为始终显示当前日期和时间?

How will this be modified to always show the present date with time?

推荐答案

基本上,您想命中服务器并按时间间隔更新结果.这称为轮询". Standard JSF没有为此内置的功能,因此您仍然需要自己编写一些JS代码(或者,从理论上讲,可以获取一个JSF组件,该组件可以为您透明地呈现所需的JS代码).在JavaScript中,您可以使用 setInterval() 来执行一个功能.

Basically, you want to hit the server and update the result at timed intervals. This is called "polling". Standard JSF has no builtin facilities for this, so you still need to write a bit of JS code yourself (or, theoretically, grab a JSF component which transparently renders the desired JS code for you). In JavaScript, you can use setInterval() to execute a function at intervals.

因此,一旦您给时间戳记组件指定了固定的ID,

So, once you give the timestamp component a fixed ID,

<h:outputText id="presentDateTime" value="#{bean.presentDateTime}" />

,然后提供以下隐藏的表单,该表单的命令按钮ajax更新了该表单,

and you supply the below hidden form whose command button ajax-updates it,

<h:form id="hiddenForm" style="display:none">
    <h:commandButton id="updatePresentDateTime">
        <f:ajax render=":presentDateTime" />
    </h:commandButton>
</h:form>

然后,您可以使用在DOM/窗口/正文就绪期间执行的以下脚本来运行它.

then you can get it to run with the below script executed during DOM/window/body ready.

<script>
    setInterval(function() {
        document.getElementById("hiddenForm:updatePresentDateTime").click();
    }, 1000);
</script>

但是,请勿在生产中将其用于此目的(客户端时钟).最多可以作为采访问题的答案(或者例如一些展示页面) .在生产中,最好与轮询"(以合理的较长时间间隔运行)结合使用,以获取纯" JS,例如: 1分钟.或者,如果您的环境支持,则通过WS或SSE使用推送.

Don't use it for this very purpose (a client side clock) in production though. It's at most OK as an answer to an interview question (or as an example in some showcase page). In production, better grab "pure" JS, if necessary in combination with a poll which runs at a reasonable longer interval, e.g. 1 minute. Or if your environment supports it, use push via WS or SSE.

这篇关于如何以1秒的间隔对组件进行Ajax更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆