使用js函数调用JSF中的后台方法,获取后台bean的return值

Use js function calls the background method in the JSF, and obtain the return value of the background bean

我不得不在JSF页面中使用HTML组件,比如下拉components.I想达到这样的目的:当我点击下拉时,选中的值会是传递给一个后台bean的方法,然后接收这个方法处理的结果,并且可以接收传递给其他js函数的值。

好的,这不是微不足道的,您会失去 JSF 的美感,但这是可能的。我将指导您如何使用 PrimeFaces 库和 <p:remoteCommand> 组件来实现这些目标:

要从 javascript 调用 JSF bean 方法,您可以使用 Primefaces 的 <p:remoteCommand/>,例如:

<script>
   function processResult(){
       //...grab result from hidden-result field by JavaScript or jQuery
   }


    function makeSelection(){
    //...code to get selected value via javascript or jQuery

       processSelection([{name:'selected', value:'<selected value>'}]);
    }
</script>
<p:remoteCommand name="processSelection" action="#{bean.processSelected}" update="hidden-result" oncomplete="processResult();" />



 <h:outputText id="hidden-result" value="#{bean.result}" style="display:none;"/>

您调用 JavaScript 函数 makeSelection 获取选定值并将其传递给 bean。然后它用 id='hidden-result' 更新字段,完成后它将调用函数 processResult ,你应该通过 JavaScript 或 jQuery 从这个字段中获取值,随心所欲地使用它。

要在支持 bean 中接收这些参数,您应该使用以下代码:

public void processSelected() {
    String selectedValue = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("param");  
   //... make whatever you want with the selected value
   result = "Result from process by JSON or plain text";
}

一开始你得到传递的参数,然后制作你的过程并将结果应用于连接到 <h:outputText/>

result 值参数

请注意我没有检查此代码,它可能包含错字

另外我推荐你看看这个问题:

  1. Pass parameter to p:remoteCommand from JavaScript
  2. How to select JSF components using jQuery?
  3. how to get managed bean property value inside javascript?