从托管 bean 调用 JavaScript 函数 [英] Calling a JavaScript function from managed bean

查看:19
本文介绍了从托管 bean 调用 JavaScript 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从 JSF 中的托管 bean 调用(执行)JavaScript 函数?

Is there a way to call (execute) a JavaScript function from managed bean in JSF?

如果这是相关的,我也在使用 PrimeFaces.

If that's relevant, I'm also using PrimeFaces.

推荐答案

PrimeFaces 6.2+

使用PrimeFaces#executeScript():

public void submit() {
    // ...
    PrimeFaces.current().executeScript("alert('peek-a-boo');");
}

注意:仅当 submit() 被 Ajax 调用时有效.

NOTE: works only when submit() is invoked by Ajax.

使用 RequestContext#execute():

public void submit() {
    // ...
    RequestContext.getCurrentInstance().execute("alert('peek-a-boo');");
}

注意:仅当 submit() 被 Ajax 调用时有效.

NOTE: works only when submit() is invoked by Ajax.

使用PartialViewContext#getEvalScripts():

public void submit() {
    // ...
    FacesContext.getCurrentInstance().getPartialViewContext().getEvalScripts().add("alert('peek-a-boo');");
}

注意:仅当 submit() 被 Ajax 调用时有效.

NOTE: works only when submit() is invoked by Ajax.

使用 Ajax#oncomplete().

public void submit() {
    // ...
    Ajax.oncomplete("alert('peek-a-boo');");
}

注意:仅当 submit() 被 Ajax 调用时有效.

NOTE: works only when submit() is invoked by Ajax.

您能做的最好的事情是将所需的脚本设置为 bean 属性,并在 bean 属性不为空时有条件地渲染 <h:outputScript> 组件.

Best what you can do is to set the desired script as a bean property and conditionally render a <h:outputScript> component when the bean property is not empty.

<h:commandButton ... action="#{bean.submit}" />
<h:outputScript rendered="#{not empty bean.script}">#{bean.script}</h:outputScript>

public void submit() {
    // ...
    script = "alert('peek-a-boo');";
}

如果您通过 Ajax 提交表单,请不要忘记将 <h:outputScript> 包装在另一个组件中,并改为使用 ajax-update 它.另请参阅 Ajax 更新/渲染不适用于具有渲染属性的组件.

In case you're submitting the form by Ajax, don't forget to wrap the <h:outputScript> in another component and ajax-update it instead. See also Ajax update/render does not work on a component which has rendered attribute.

<h:commandButton ... action="#{bean.submit}">
    <f:ajax execute="@form" render="script" />
</h:commandButton>
<h:panelGroup id="script">
    <h:outputScript rendered="#{not empty bean.script}">#{bean.script}</h:outputScript>
</h:panelGroup>

这篇关于从托管 bean 调用 JavaScript 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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