简体   繁体   中英

Call a JSF method via JS

i have a for loop in JS code, i want to call a method with parameters written in a JAVA managed bean that calculate a value and return a new one that will be used in the JS Note: i'm using primefaces in the xhtml page and handsontable to display data

that's how my js looks like

function updateMoneyValue(){
   var thetable; //the handsonTable
   for (var i =0 ; i < thetable.length ; i++)
      {
         var myNewValue = theBeanMethod (firstParam , secondParam);
      }
}

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. This example demonstrates a use case where a certain part of a page can be lazily loaded on demand.

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"));
}

There's no way to do that directly.

Your java/jsf code is parsed and executed on server and then sent to client (browser). Only in browser javascript starts executing.

If you want to call some bean's method and get the result from client/javascript, you need to initiate new network request via AJAX call or somewhat. Also you can try to rework the logic of your application.

you can use primefaces remoteCommand component. you can find details about remoteCommand in this blog post.

http://blogs.bytecode.com.au/glen/2013/09/25/calling-primefaces-remotecommand-with-javascript-arguments.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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