Getting backing bean value with Javascript

后端 未结 2 875
予麋鹿
予麋鹿 2020-11-28 12:06

JSF 2.0, Mojarra 2.0.1, PrimeFaces 3.4.1

There are similar questions but I need sth. else; javascript function has to wait for the backing bean method, whic

相关标签:
2条回答
  • 2020-11-28 12:37

    JSF/EL and HTML/JS doesn't run in sync. Instead, JSF/EL run in webserver and produces HTML/JS which in turn runs in webbrowser. Open page in browser, rightclick and View Source. You see, there's no single line of JSF/EL. It's one and all HTML/JS. In place of your JS function, you'll see:

    function afterLoad() {    
        alert("0");
    }
    

    Exactly this JS function get invoked on complete of your command button action. So the result is fully expected.

    Basically, you want to let JSF re-render that piece of JS.

    <p:commandLink action="#{statusBean.getStatuses}" update="afterLoad" oncomplete="afterLoad()"/>
    <h:panelGroup id="afterLoad">
        <h:outputScript>
            function afterLoad() {    
                alert("#{statusBean.size}");
            }
        </h:outputScript>
    </h:panelGroup>
    

    Depending on the concrete functional requirement, which you didn't tell anything about, there may be more elegant ways. For example, RequestContext#execute(), <o:onloadScript>, etc.

    0 讨论(0)
  • 2020-11-28 12:47

    EL in your JavaScript is calculated when page is rendered and you can update its container (if it is in some JSF component), but I would suggest another approach.

    As you are making AJAX request, you can add callback parameter in getStatuses() method. You can use Primefaces's RequestContext utility method addCallBackParam() for this:

    public void getStatuses() {
        this.panelList = fillList();
        this.size = panelList.size();
        RequestContext.getCurrentInstance().addCallBackParam("size", this.size);
    }
    

    and you can use this parameter in xhtml:

    <p:commandLink action="#{statusBean.getStatuses}" oncomplete="afterLoad(xhr, status, args)"/>
    
    <script type="text/javascript">
      function afterLoad(xhr, status, args) {    
        alert(args.size);
      }
    </script>
    
    0 讨论(0)
提交回复
热议问题