Ajax + JSON

JSONを少しいじったからメモ&備忘録ですよ。

サーバーの設定

debianユーザーはapt使うと楽チン。
aptitude install php5-json

動いているか以下のスクリプトで確認。ファイル名は sample_1.php

<?php
$arr = array('xxxx','yyyy','zzzz',array('1111',2222));
$encoded = json_encode($arr);
echo $encoded."\n";
<||

>||
kasuya@proc:~/blog/pear_json$ php sample_1.php
["xxxx","yyyy","zzzz",["1111",2222]]   # わーい

Ajax を使って取得

こんな感じで作ってみる
<html>
<script src='prototype.js'></script>
<body>
<ul>
<li><a href='sample_1.phps'>sample_1.phpのソース</a></li>
<li><a href='sample_1.php'>sample_1.phpの実行結果</a></li>
</ul>
<hr>
リクエスト先URL:<input type='text' id='url' maxlength='256' value='sample_1.php'>
<input type='button' onclick='eval(this.value)' value='Request();'>
<hr>
リクエスト結果:<div id='result'>Result</div>
</body>
<script>
function Request() //{{{
{
  var url = $('url').value;
  new Ajax.Request(url,
      {
        method:'GET',
        paramters:'',
        onSuccess:Success,
        onFailure:Failure
      });

} //}}}

function Success(httpObject) //{{{
{
  var text = httpObject.responseText;
  var json 
  eval('json = ' + text);
  $('result').innerHTML = json.toString();

  alert('success');
} //}}}

function Failure(httpObject) //{{{
{
  alert('failure');
} //}}}

// Array の文字列化
Array.prototype.toString = function() { //{{{
  var result = ''; 
  result = 'Array('+this.join(',')+')';
  return result;
}; //}}}
</script>
</html>

動いているのは http://kasuya.mobi/blog/php-json/ajax.html でみれるので、ソースの解説を。

HTMLソース解説
  • ボタンを押す
  • Request() function を実行する
    • リクエスト先URL を テキストボックスから持ってきて、非同期でアクセスしに行く
  • リクエスト先からデータを受け取ったら、Success()が呼び出される
    • httpObjectから、受信したテキストを取得
    • eval()でjson変数に代入する
    • リクエスト結果に出力する

結果


できたー。わーい。