/bonvhp/webapp/prototype_js       [後へ]   [目次へ]   [次へ] ~ [] ~

prototype.js:Ajax

●Ajax.Request

Ajax は、
より使いやすい WEB にするための必須アイテムといっていいでしょう。
# Ajax そのものの説明は省略します。

が、
Ajax の使い方は、ブラウザによって様々で、
何かとコーディングが面倒です。
prototype.js の Ajax.Request を使えば、面倒さが軽減されます。

最低限、以下のコードがあれば動作します。

<script type="text/javascript"> <!-- // 通信したいときに、subFunc を呼ぶ function subFunc() { new Ajax.Request("targetURL", { // 必要なオプションがあれば書く // mtype: 通信方式 ('get', 'post' など。デフォルトは post。省略可) // postBody : mtype が post の場合に送信するデータ (省略可) // asynchronous: 非同期通信するか (true または false。デフォルトは true。省略可) onSuccess:function(response) { // 通信に成功したときに呼ばれる // response.responseText にサーバーから来たデータが入っている }, onFailure:function(response) { // 通信に失敗したときに呼ばれる } }); } // --> </script>
簡単な実例を挙げます。 以下に示す ajax.php、ajax.html と、 prototype.js 本体ファイルを、 c:\Apache24\htdocs 直下に置きます。 ブラウザで、ajax.html を開きます。 ボタンを押すと、 "testtest100: return from the server" とポップアップが出れば OK です。 ・ajax.php
<?php // Ajax.Request から呼ばれる。 // 実運用では、 // ここでデータベースにアクセスするなど、 // 普通の PHP コードが使える。 // 画面表示した内容そのままが Ajax の結果として帰る。 print_r($_GET["getParam"].$_POST["postParam"].": return from the server"); ?>
・ajax.html:
<html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <script type="text/javascript" src="prototype.js"></script> <script type="text/javascript"> <!-- function subFunc() { new Ajax.Request("ajax.php?getParam=testtest", { postBody: "postParam=100", onSuccess:function(response) { // 通信に成功したときに呼ばれる。 // 厳密には、response.status が 200 な事を確認すべし。 alert(response.responseText); }, onFailure:function(response) { // 通信に失敗したときに呼ばれる alert("ERROR!!"); } }); } // --> </script> </head> <body> <input type="button" value="ボタン" onClick="subFunc()"> </body> </html>
さらに言うと、 PHP からの結果が文字列1つなら上記でいいのですが、 配列など、複数のデータを渡したい場合は、 JSON を使うといいでしょう。 ・渡したいデータを JSON 形式で print_r する。 上記の例だと、 print_r($_GET["getParam"].$_POST["postParam"].": return from the server"); の部分を、 $ret=array($_GET["getParam"].$_POST["postParam"]=>"return from the server"); print_r(json_encode($ret)); などとします。 # json_encode は、PHP 5.2.0 以上で使えます。 ・Ajax のほうで、改めて JSON をオブジェクトに変換して使う。 上記の例だと、 alert(response.responseText); の部分を、 var ret=response.responseText.evalJSON(); alert(ret['testtest100']); などとします。
/bonvhp/webapp/prototype_js       [後へ]   [目次へ]   [次へ]