如何通过ajax刷新由JSF填充的javascript变量? [英] How can I refresh a javascript variable, populated by JSF, via ajax?
问题描述
我想要执行以下操作:
- 从
中选择一项h:selectOneMenu
- 使用新值通过ajax更新支持bean
- 使用新值运行Javascript函数
在下面的代码中, alert(#{backingBean.derivedValue})
仍包含来自的值最后一次更改(即当我选择Two时为0,当我选择One时为4,依此类推):
In the following code though, alert(#{backingBean.derivedValue})
still contains the value from the last change (i.e. it's 0 when I select "Two", 4 when I select "One", and so on):
<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>
支持豆:
@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协同工作,但不是这个特定的问题)
Is there a way to do this? (BTW, I've read countless threads on this site which kind of/sort of deal with JSF/ajax/javascript working together, but not this specific issue)
推荐答案
我成功实现了本答案中提出的解决方案,使用Javascript获取支持bean值它使用 PrimeFace的RequestContext 添加Javascript回调参数服务器端。
I had success implementing the solution proposed in this answer, Getting backing bean value with Javascript which uses PrimeFace's RequestContext to add a Javascript callback parameter server-side.
这是我的Facelets页面:
Here is my Facelets page:
<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的解决方案。)
(I don't know if this is a good solution for integrating JSF and D3.)
- Getting backing bean value with Javascript
这篇关于如何通过ajax刷新由JSF填充的javascript变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!