【问题标题】:Using backing bean value in javascript在 javascript 中使用支持 bean 值
【发布时间】:2014-02-19 10:41:24
【问题描述】:
   <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);
        }
    }

在这里,alert(#{test.i}) 始终显示 0。当我单击命令按钮时,我如何获得改变的支持 bean 值。 当我点击两次按钮时它工作正常。当我使用 a4j:commandButton 时它工作正常。

【问题讨论】:

    标签: jsf-2 primefaces richfaces


    【解决方案1】:

    与可以直接调用javascript函数的Richfaces不同,primefaces需要有javascript函数:

    function_name(xhr, status, args)

    以列出的 CommandButton 为例:

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

    在函数 test.testfxn() 中我们有:

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

    在这里,在从 actionlistener 到 backing bean 的函数调用中,变量被添加到 RequestContext。

    现在在javascript函数中:

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

    【讨论】:

      【解决方案2】:

      这是因为alert(#{test.i}); 在commandButton 被渲染 时被评估。您可以通过告诉 JSF 再次渲染脚本来查看更改的值:

      <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>
      

      【讨论】:

      • 我用过oncomplete。这还不够吗?
      • oncomplete 在视图渲染时渲染。这就是评估您的#{test.i} 的时间。 ajax 请求完成时不会更新。所以你需要告诉 JSF 把你更新的 i 放在某个地方(也许让它呈现一个隐藏的输入,你可以从 oncomplete 函数中读取它)。
      • 如何实时更改。我用richfaces做了这个,它工作正常。然后当我用 primefaces 做它时它不起作用。
      • @kinkajou 请提出一个新问题,并确保包含有效的richfaces 代码以及失败的primefaces 变体。
      • 您的意思是您最初发布的代码在使用&lt;a4j:commandButton&gt; 时有效?这可能是因为 RF 更新了触发该操作的组件。在 Primefaces 的 commandButton 上尝试update="@this"。
      猜你喜欢
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多