Using backing bean value in javascript

穿精又带淫゛_ 提交于 2019-12-04 05:55:05

问题


   <h:form prependId="false" id="vt_sel_form">
         <p:panelGrid styleClass="center" columns="2">                     
                        <p:commandButton value="GO" oncomplete="alert(#{test.i})"  actionListener="#{test.testfxn()}" update="@this"/>
         </p:panelGrid>
    </h:form>

  import java.io.Serializable;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.ViewScoped;

    @ViewScoped
    @ManagedBean(name = "test")

    public class TestClass implements Serializable {

        int i ;

        public int getI() {
            return i;
        }

        public void setI(int i) {
            this.i = i;
        }

        public void testfxn() {        
            setI(i++);
            //i=i+10;
            System.out.println("i" + i);
        }
    }

Here, alert(#{test.i}) is always displaying 0. How do i get backing bean value that changes when I click the commandButton. It works when I click button twice. It used to work fine when I used a4j:commandButton.


回答1:


That's just because alert(#{test.i}); is evaluated when the commandButton is rendered. You can see the changed value by telling JSF to render the script again:

<h:commandButton value="click me" action="#{testClass.testfxn()}">
    <f:ajax render="out" />
</h:commandButton>
<h:panelGroup id="out">
    <h:outputScript>
         alert(#{testClass.i});
    </h:outputScript>
</h:panelGroup>



回答2:


Unlike Richfaces where you can directly call javascript function, primefaces you need to have javascript function as:

function_name(xhr, status, args)

Using listed CommandButton as Example:

 <p:commandButton value="GO" oncomplete="alert(#{test.i})"  actionListener="#{test.testfxn()}" update="@this"/>

In function test.testfxn() we have:

public void testfxn(){    
RequestContext reqCtx = RequestContext.getCurrentInstance();
        i = i++;
        reqCtx.addCallbackParam("i", i);
}

Here,In function call to backing bean from actionlistener the variables are added to RequestContext.

Now In javascript function:

function draw(xhr, status, args) {
    console.log("We are into draw function");
    jsonString = JSON.parse(args.i); //json variable is taken out from args variable.
    console.log("The value of i "+ i);
}


来源:https://stackoverflow.com/questions/21400407/using-backing-bean-value-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!