フォーム送信をAjaxで実行&画面更新までできるApplicationController(その1)「基本的な使い方」
最近のWebアプリケーションではAjaxを使うのが当たり前になっています。そしてAjaxでフォームデータを送信した後、データをハンドリングして画面を更新したりします。これはよくあるコードであり、最近の開発でよくいうDRY(Don’t repeat yourself)に反すると言えます。
hifiveではそのようなごく基本的なAjax処理についてApplicationControllerでほぼコーディングなしで実装できるようになっています。今回はその基本形の紹介です。
例えば次のような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="app.jsp"> | |
<label>名前</label><input type="text" id="name" name="name" value="たろう" /> | |
<p data-h5-bind="message">名前を入力して送信ボタンをクリックしてください</p> | |
<input type="submit" /> | |
</form> |
これは app.jsp に対してnameデータを送信するものと言えます。これに対してhifiveで次のように h5.ui.container.ApplicationController を適用します。
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); | |
}); |
これで実行するとWebブラウザは表示をリフレッシュせず、Ajaxで送信を行います。そして結果をそのままフォーム全体にして適用します。
この時のレスポンスはサーバからHTMLをそのまま返しています。
実際のデモはこちらにて確認できます。サーバ送信部分はモックですが、サーバを立てた場合と同じです。
インジケータを出すような表示も自動で行ってくれます。ApplicationControllerを使えばAjax実装がごく簡単になるでしょう。
コメントは受け付けていません。