使用 JSF 的 valueChangeListener、onchange 和自动提交表单

valueChangeListener, onchange and auto-submission of form using JSF

对于像这样的简单 html 页面:

<form action="success.html" >

        <input type="text" value="SomeValue" onchange="this.form.submit()"/>
        <input type="submit" value="Submit"/>

</form>

值的任何更改都会导致 自动提交表单 以导航到 success.html

考虑 JSF 中的以下代码片段 2.x:

<h:form >

        <h:panelGrid columns="3">

            <h:outputLabel value="Name: " />
            <h:inputText id="inputname" binding="#{zipAutoFill.inputName}" 
                                        required="true"/>
            <h:message for="inputname"/>

            <h:outputLabel value="Zip Code: " />
            <h:inputText id="inputzip" 
                         binding="#{zipAutoFill.inputZip}" 
                valueChangeListener="#{zipAutoFill.zipAutoFillListener}"
                                        onchange="this.form.submit()"/>
                                        <h:message for="inputzip"/>

            <h:outputLabel value="City: " />
            <h:inputText id="inputcity" binding="#{zipAutoFill.inputCity}" />
            <h:message for="inputcity"/>

            <h:outputLabel value="State: " />
            <h:inputText id="inputstate" binding="#{zipAutoFill.inputState}" />
            <h:message for="inputstate"/>

            <h:commandButton  id="submitbutton" value="Submit" action="page02"/>

        </h:panelGrid>


</h:form>

根据用户填写的邮政编码(因此导致值发生变化),将相应地填充城市和州字段。

但是,在自动提交后,它不会导航到 page02.xhtml。我错过了什么?

在您使用简单 HTML 的第一个示例中,提交后导航背后的原因与 action 属性有关,该属性由您要发送的页面名称指定您的数据到 <form action="success.html" >,因此您的 this.form.submit() 会将表单数据发送到 success.html 并导航到它。

要了解在使用 JSF 自动提交的情况下未显示第二页的原因,您可以查看生成的 HTML。在您的 JSF 示例中,并且因为您使用的是 <h:commandButton>,生成的 HTML 看起来像这样(为简单起见,我假设您的表单 ID 是 form 并且您的 current第 页是 page01.xhtml):

<form id="form" name="form" method="post" action="/yourcontextpath/page01.xhtml" enctype="application/x-www-form-urlencoded">
    <input type="hidden" name="form" value="form" />
    .....

    <input type="submit" name="form:submitbutton" value="Submit" />

</form>

因此,您可以注意到生成的 HTML 的 action 属性设置为您的当前页面 action="/yourcontextpath/page01.xhtml",这意味着对 JavaScript 的任何调用submit() 会将表单数据发送到当前页面,在我们的例子中是 page01.xhtml(与第一个示例不同,表单数据被发送到另一个页面 success.html)。

简而言之,您不会有相同的行为,因为 HTML 代码不相同(比较第一个示例和生成的 HTML),主要区别是相关的到表单的 action 属性中指定的页面。

注意: 如果您使用 <h:commandButton> 提交,结果将不同,因为 JSF 将使用 commandButton 的 action 属性的结果导航到 page02.xhtml<h:commandButton id="submitbutton" value="Submit" action="page02"/>

中指定

另请参阅:

  • Difference between h:button and h:commandButton