从 javascript 更新 bean
updating bean from javascript
我有一个 .xhtml 页面,我从中启动了一个 javascript,在这个 javascript 我想更新一个 bean 的内容,我发现最简单的方法是通过添加隐藏形式并将所述 bean 的 属性 链接到它的值:
index.xhtml
<h:form id="poi-form" styleClass="invisible">
<h:inputHidden id="poi" value="#{userBean.email}" />
</h:form>
javascriptfile.js
function handleEmailResponse(resp) {
document.getElementById('poi-form:poi').value = 'usersNewEmailValue';
window.location.replace("timeline.xhtml");
}
但是,timeline.xhtml 中的值不是我预期的值(好像它没有更新),因为我看到
中设置的用户旧电子邮件值
userBean.java
@PostConstruct
public void init() {
email = "usersOldEmailValue;
}
我是不是忘记了什么?预先感谢您的帮助!
您实际上是忘记提交表单,因此服务器端可以更新您的模型。
此外,如果您使用 PrimeFaces,您也可以使用 p:remoteCommand。
使用以下代码修复:
index.xhtml
<h:form id="poi-form" styleClass="invisible">
<input type="text" id="poiemail" name="poiemail" />
<h:commandButton action="#{userBean.updateData()}" id="miAwesomeButton" value="I'm clicked by javascript"/>
</h:form>
javascriptfile.js
function handleEmailResponse(resp) {
document.getElementById('poiemail').value = 'usersNewEmailValue';
document.getElementById('poi-form:miAwesomeButton').click();
}
userBean.java
public String updateData() {
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
this.email= request.getParameter("poiemail");
return "redirectURL";
}
我有一个 .xhtml 页面,我从中启动了一个 javascript,在这个 javascript 我想更新一个 bean 的内容,我发现最简单的方法是通过添加隐藏形式并将所述 bean 的 属性 链接到它的值:
index.xhtml
<h:form id="poi-form" styleClass="invisible">
<h:inputHidden id="poi" value="#{userBean.email}" />
</h:form>
javascriptfile.js
function handleEmailResponse(resp) {
document.getElementById('poi-form:poi').value = 'usersNewEmailValue';
window.location.replace("timeline.xhtml");
}
但是,timeline.xhtml 中的值不是我预期的值(好像它没有更新),因为我看到
中设置的用户旧电子邮件值userBean.java
@PostConstruct
public void init() {
email = "usersOldEmailValue;
}
我是不是忘记了什么?预先感谢您的帮助!
您实际上是忘记提交表单,因此服务器端可以更新您的模型。
此外,如果您使用 PrimeFaces,您也可以使用 p:remoteCommand。
使用以下代码修复:
index.xhtml
<h:form id="poi-form" styleClass="invisible">
<input type="text" id="poiemail" name="poiemail" />
<h:commandButton action="#{userBean.updateData()}" id="miAwesomeButton" value="I'm clicked by javascript"/>
</h:form>
javascriptfile.js
function handleEmailResponse(resp) {
document.getElementById('poiemail').value = 'usersNewEmailValue';
document.getElementById('poi-form:miAwesomeButton').click();
}
userBean.java
public String updateData() {
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
this.email= request.getParameter("poiemail");
return "redirectURL";
}