フォームを送信し、マネージド Bean アクションを呼び出すボタンがあります。
<h:form>
...
<h:commandButton value="Submit" action="#{bean.submit}" />
</h:form>
しかし、ボタンを押すとページ全体が更新され、URL が変更されることもあります。
ページを更新せずにアクションを呼び出す方法はありますか?
フォームを送信し、マネージド Bean アクションを呼び出すボタンがあります。
<h:form>
...
<h:commandButton value="Submit" action="#{bean.submit}" />
</h:form>
しかし、ボタンを押すとページ全体が更新され、URL が変更されることもあります。
ページを更新せずにアクションを呼び出す方法はありますか?
Ajax を利用します。<f:ajax>
対象のコマンド ボタン内にネストするだけです。
<h:form>
...
<h:commandButton ...>
<f:ajax execute="@form" render="@none" />
</h:commandButton>
</h:form>
特に、render="@none"
(これはデフォルト値ですが、属性を完全に省略できます) は、送信後に何も再レンダリングしないように JSF に指示します。ページ全体ではなく特定のコンポーネントのみを再レンダリングする場合は、その特定のコンポーネントの ID をrender
属性で指定することもできます。
<h:form>
...
<h:commandButton ...>
<f:ajax execute="@form" render="result" />
</h:commandButton>
...
<h:panelGroup id="result">...</h:panelGroup>
</h:form>
すでに PrimeFaces を使用している場合は、<p:commandButton>
代わりに を使用するだけです<h:commandButton>
。デフォルトですでに ajax を使用しているため、 にネストする必要はありません<f:ajax>
。andの代わりに属性名process
andを使用することを覚えておく必要があるだけです。update
execute
render
<h:form>
...
<p:commandButton ... update="result" />
...
<h:panelGroup id="result">...</h:panelGroup>
</h:form>
execute
属性のデフォルトは@form
already であるため、省略できます。