You can use PrimeFaces remote command component (<p:remoteCommand>
).
RemoteCommand enables executing backing bean methods and do partial
update triggered by custom client side script.
Add it to the view it in a following way:
<p:remoteCommand name="myRemote" actionListener="#{myBean.listen}"/>
And use it in Javascript like so:
<script type="text/javascript">
myRemote(); //makes a remote call
</script>
or call it from an event handler like so:
<div onclick="myremote();">...</div>
If you additionally want to pass parameters to the server make a following call:
<script type="text/javascript">
myRemote([{name:'param1', value:150}, {name:'param2', value:220}]); //makes a remote call with parameters
</script>
The listener could be like:
public void listen(){
FacesContext context = FacesContext.getCurrentInstance();
Map<String,String> params = context.getExternalContext().getRequestParameterMap();
System.out.println(params.get("param1"));
System.out.println(params.get("param2"));
}
One of the comments asked to return a Value to Javascript.
Well in that case you can use Primeface's Request Context's execute() method to execute any javascript you want.
RequestContext.getCurrentInstance().execute("your javascript code");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…