如何通过ajax刷新由JSF填充的javascript变量?

时间:2015-04-09 19:25:27

标签: javascript ajax jsf

我想做以下事情:

  1. h:selectOneMenu
  2. 中选择一个项目
  3. 使用新值(通过ajax
  4. )更新辅助bean
  5. 使用新值运行Javascript函数
  6. 在下面的代码中,alert(#{backingBean.derivedValue})仍然包含上次更改的值(即,当我选择“Two”时它为0,当我选择“One”时为4,依此类推):

    <h:form>
        <h:selectOneMenu value="#{backingBean.input1}">
            <f:selectItem itemLabel="One" itemValue="1"/>
            <f:selectItem itemLabel="Two" itemValue="2"/>
            <f:ajax render="@form" onevent="function(data) { if (data.status === 'success') { alert(#{backingBean.derivedValue}) }}"/>
        </h:selectOneMenu>
    
        Input value: #{backingBean.input1}
        Derived value: #{backingBean.derivedValue}
    </h:form>
    

    支持bean:

    @ManagedBean
    @ViewScoped
    public class BackingBean {
    
        private int input1;
        private int derivedValue;
    
        public int getDerivedValue() {
            return derivedValue;
        }
    
        public void setDerivedValue(int derivedValue) {
            this.derivedValue = derivedValue;
        }
    
        public int getInput1() {
            return input1;
        }
    
        public void setInput1(int input1) {
            this.input1 = input1;
            derivedValue = input1 * 2;
        }
    }
    

    有办法做到这一点吗? (顺便说一句,我在这个网站上读过无数线程,这种线程与JSF / ajax / javascript协同工作,但不是这个特定的问题)

1 个答案:

答案 0 :(得分:1)

我成功实现了此答案中提出的解决方案,Getting backing bean value with Javascript使用PrimeFace's RequestContext添加Javascript回调参数服务器端。

这是我的Facelets页面:

<h:form>
    <p:selectOneMenu value="#{backingBean.input1}">
        <f:selectItem itemLabel="One" itemValue="1"/>
        <f:selectItem itemLabel="Two" itemValue="2"/>
        <p:ajax oncomplete="afterLoad(xhr, status, args)"/>
    </p:selectOneMenu>
    <h:outputScript>
        function afterLoad(xhr, status, args) {    
          alert("Input * 2 = " + args.derived);
        }
    </h:outputScript>
</h:form>

这是我的支持豆:

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.primefaces.context.RequestContext;

@ManagedBean
@ViewScoped
public class BackingBean {

    private int input1;
    private int derivedValue;

    public int getDerivedValue() {
        return derivedValue;
    }

    public void setDerivedValue(int derivedValue) {
        this.derivedValue = derivedValue;
    }

    public int getInput1() {
        return input1;
    }

    public void setInput1(int input1) {
        this.input1 = input1;
        derivedValue = input1 * 2;
        RequestContext.getCurrentInstance().addCallbackParam("derived", derivedValue);
    }
}

(我不知道这是否是集成JSF和D3的好方法。)

另见