猿问

请问怎么从托管bean调用JavaScript函数

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

如果合适的话,我也在使用PrimeFaces。


Cats萌萌
浏览 393回答 3
3回答

温温酱

在PrimeFaces 6.2之前的版本中,您可以使用RequestContext#execute()此功能。public void submit() {&nbsp; &nbsp; // ...&nbsp; &nbsp; RequestContext.getCurrentInstance().execute("alert('peek-a-boo');");}在PrimeFaces 6.2及更高版本中:public void submit() {&nbsp; &nbsp; // ...&nbsp; &nbsp; PrimeFaces.current().executeScript("alert('peek-a-boo');");}在标准JSF中,没有直接的公共API。最好的办法是将所需的脚本设置为bean属性,并<h:outputScript>在bean属性不为空时有条件地呈现组件。<h:commandButton ... action="#{bean.submit}" /><h:outputScript rendered="#{not empty bean.script}">#{bean.script}</h:outputScript>public void submit() {&nbsp; &nbsp; // ...&nbsp; &nbsp; script = "alert('peek-a-boo');";}如果您要通过ajax提交表单,请不要忘记将其包装<h:outputScript>在另一个组件中,然后用ajax更新它。另请参见Ajax update / render在具有rendered属性的组件上不起作用。<h:commandButton ... action="#{bean.submit}">&nbsp; &nbsp; <f:ajax execute="@form" render="script" /></h:commandButton><h:panelGroup id="script">&nbsp; &nbsp; <h:outputScript rendered="#{not empty bean.script}">#{bean.script}</h:outputScript></h:panelGroup>至于“没有直接的公共API用于该语句”,奇怪的是,PartialResponseWriter该类(负责编写JSF ajax响应)自JSF 2.0 startEval()和endEval()方法以来就已经存在,它们应该使您能够直接向响应编写回调脚本,但要等到即将发布的JSF 2.3为止令人惊讶的是,没有任何公共方法PartialViewContext可以委托这些方法。根据问题1412 PartialViewContext#getEvalScripts(),最终被添加到公共API。public void submit() {&nbsp; &nbsp; // ...&nbsp; &nbsp; FacesContext.getCurrentInstance().getPartialViewContext().getEvalScripts().add("alert('peek-a-boo');");}对于较旧的JSF版本,只能通过创建自定义PartialViewContext实现来实现。JSF实用程序库OmniFaces完全OmniPartialViewContext可以通过Ajax实用程序类使用它。public void submit() {&nbsp; &nbsp; // ...&nbsp; &nbsp; Ajax.oncomplete("alert('peek-a-boo');");}

杨魅力

根据您所使用的Primefaces版本,可以使用 RequestContext.execute("{js here}");从Primefaces 3.4文档中:RequestContext提供了一种在ajax请求完成时执行javascript的方法,与传递回调参数和执行条件javascript相比,此方法更容易。下面的示例在ajax请求完成时隐藏对话框。码public void save() {&nbsp; RequestContext requestContext = RequestContext.getCurrentInstance();&nbsp;&nbsp;&nbsp; requestContext.execute("dialog.hide()");}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答