从托管 bean 调用 JavaScript 函数 [英] Calling a JavaScript function from managed bean
问题描述
有没有办法从 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+
public void submit() {
// ...
PrimeFaces.current().executeScript("alert('peek-a-boo');");
}
注意:仅当 submit()
被 Ajax 调用时有效.
NOTE: works only when submit()
is invoked by Ajax.
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.
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屋!