フォーム送信をAjaxで実行&画面更新までできるApplicationController(その3)「要素の追加、更新」
引き続きApplicationControllerを使ったAjax処理の省力化について紹介します。今回は要素の追加(前後)と更新についてです。
サーバからのレスポンスに対して、その結果をHTML内に追加したい時と、元のHTMLを書き換えたい場合があります。ApplicationControllerでは h5-bind-target を使って指定できます。
HTMLは次のようになります。appendが後ろに追加、prependが前に追加そしてupdateがHTMLの内容を更新するという指定になります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form action="jsp/welcome-json.jsp"> | |
<label>名前</label><input type="text" id="name" name="name" value="たろう" /> | |
<p h5-bind-target="append">後に追加:</p> | |
<p h5-bind-target="prepend">前に追加:</p> | |
<p h5-bind-target="update">更新:</p> | |
<input type="submit" /> | |
</form> |
JavaScript側は次のように特に変わりません。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function() { | |
h5.core.controller('body', h5.ui.container.ApplicationController); | |
}); |
これを実行すると次のようになります。
それぞれ表示結果が異なるのが分かるかと思います。
実際のデモはこちらにて確認できます。サーバ送信部分はモックですが、サーバを立てた場合と同じです。
リスト要素への追加であれば前後、どちらの可能性もあります。結果をメッセージとして表示するのであればupdateを指定するのが良いでしょう。目的に応じて使い分けてください。
コメントは受け付けていません。