我想做以下事情:
h:selectOneMenu
在下面的代码中,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协同工作,但不是这个特定的问题)
答案 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的好方法。)