How to invoke a JSF managed bean on a HTML DOM event using native JavaScript?

后端 未结 1 2051
傲寒
傲寒 2020-11-22 01:39

I need to execute a JSF managed bean action method using ajax during HTML DOM load event, similar to jQuery\'s $(document).ready(function() { $.ajax(...)

1条回答
  •  名媛妹妹
    2020-11-22 02:01

    Several ways.

    1. Use . Note that this is only available since JSF 2.3.

      
          
      
      
          ...
      
      

      You can invoke it in JS as below:

      commandName();
      

      The parameters can be passed as below:

      commandName({ name1: "value1", name2: "value2" });
      

      And obtained as below:

      String name1 = externalContext.getRequestParameterMap().get("name1"); // value1
      String name2 = externalContext.getRequestParameterMap().get("name2"); // value2
      

      To invoke it during load event, set autorun="true".

      
      

    2. If you're using PrimeFaces, use its .

      
          
      
      
          ...
      
      

      You can invoke it in JS as below:

      commandName();
      

      This however doesn't use JSF native jsf.ajax.request(), instead it uses PrimeFaces native jQuery (you know, PrimeFaces is a JSF component library on top of jQuery/UI).

      The parameters can be passed as below:

      commandName([{ name: "name1", value: "value1" }, { name: "name2", value: "value2" }]);
      

      And obtained as below:

      String name1 = externalContext.getRequestParameterMap().get("name1"); // value1
      String name2 = externalContext.getRequestParameterMap().get("name2"); // value2
      

      To invoke it during load event, set autoRun="true".

      
      

    3. If you're using OmniFaces, use its . The usage is exactly the same as with but then available for older JSF 2.x versions.

      Simply replace h: by o: in the first example. Historical note: the is entirely based off .


    4. Use the "hidden form" trick (actually, "hack" is given the ugliness a better wording).

      
      
          ...
      
      

      You can invoke it in JS as below:

      document.getElementById("form:button").onclick();
      

      Note the importance of triggering onclick() instead of click() in case of . The onclick() immediately invokes the onclick function while the click() only triggers the "click" event on the element, which is not supported in IE. If you were using a , you can safely use click() instead.

      You can pass parameters via in same form which you fill by JS beforehand. This is demonstrated in How to pass JavaScript variables as parameters to JSF action method?

      To invoke it during load event, consider putting it in . The target="body" automatically puts the

提交回复
热议问题