简体   繁体   English

无法从javascript调用backing bean方法

[英]Can not call backing bean method from javascript

I try to write javascript code in bean method. 我尝试用bean方法编写javascript代码。 I am successful at this in application start. 在应用程序启动方面,我很成功。

When I run my application, the js function calls the bean method and return values, however when I click to button it never calls again. 当我运行我的应用程序时,js函数调用bean方法并返回值,但是当我单击按钮时,它再也不会调用。 I mean, It only calls the bean method while application is starting. 我的意思是,它仅在应用程序启动时调用bean方法。 My button is: 我的按钮是:

<p:commandLink oncomplete="myRemote();" title="my button"
               />

My javascript function is: 我的JavaScript函数是:

 function myRemote() {
 ${myBackingBean.actionMyValues()}

 }

My Bean is: 我的豆是:

@Controller
@Scope("view")
public class MyBackingBean implements Serializable {


public String actionMyValues() {

    String js="";
    /*getting some values from database and adding it to javascript variables.*/
    js += "alert('alert')";//
    return js;
}
}

If you want to call JS from your backing bean you can use the org.primefaces.context.RequestContext class: 如果要从备用Bean调用JS,则可以使用org.primefaces.context.RequestContext类:

String js="";
/*getting some values from database and adding it to javascript variables.*/
js += "alert('alert')";
RequestContext.getCurrentInstance().execute("js");

EDIT 编辑

As it has been suggested in the comments you can also use a p:remoteCommand ( https://www.primefaces.org/showcase/ui/ajax/remoteCommand.xhtml ) 正如评论中所建议的,您还可以使用p:remoteCommandhttps://www.primefaces.org/showcase/ui/ajax/remoteCommand.xhtml

The remote command would replace your custom JS function: 远程命令将替换您的自定义JS函数:

<p:commandButton value="My button" type="button" onclick="myRemote()" id="btnRemote" />  

<p:remoteCommand name="myRemote" actionListener="#{myBackingBean.actionMyValues()}"/>   

Then if you need to call JS from your bean you still need to use the RequestContext . 然后,如果您需要从bean中调用JS,则仍然需要使用RequestContext

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM