フォーム送信をAjaxで実行&画面更新までできるApplicationController(その2)「要素のバインディング」
Ajax処理がごく簡単になるApplicationControllerを紹介します。前回はHTML全体を書き換えていましたが、それでは再送できなかったり、不便なことがあるかも知れません。
そこで今回は名前を指定して画面上の一部を更新する方法を紹介します。
今回の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 data-h5-bind="message">名前を入力して送信ボタンをクリックしてください</p> | |
<input type="submit" /> | |
</form> |
そしてApplicationControllerも前回と同じです。たったこれだけでサーバへのAjax送信、インジケータ表示、レスポンスのハンドリングができます。
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); | |
}); |
サーバからのレスポンスですが、text/jsonで返すのが特徴です。そしてHashの中でキーと値で新しいコンテンツを返します。
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
// ダミー実行 | |
$.ajax = function(data) { | |
var name = $("#name").val(); | |
var deffered = h5.async.deferred(); | |
var p = deffered.promise(); | |
p.dataTypes = ["text", "json"]; | |
setTimeout(function() { | |
deffered.resolve({ | |
message: name+"さん、こんにちは" | |
}); | |
}, 1000); | |
return p; | |
} |
これで実行するとフォーム内の一部だけを更新するようになります。
実際のデモはこちらにて確認できます。サーバ送信部分はモックですが、サーバを立てた場合と同じです。
ApplicationControllerを使えばAjax処理が簡単になるでしょう。
コメントは受け付けていません。