CodeIgniterでAjaxを使う
Ajaxを使うときに、いつも忘れていて調べることから始まるので、ブログに簡単なサンプルをまとめておく。
CodeIgniterの出力クラスを使えば、簡単にJSONを返すコントローラが作れる。FuelPHPならRestコントローラで楽勝。
サーバ側(コントローラ)
<?php class Ajax extends CI_Controller{ public function __construct(){ parent::__construct(); } public function index(){ // サーバ側でもってるデータ $array = array( array('framework' => 'codeigniter', 'lang' => 'php',), array('framework' => 'fuelphp', 'lang' => 'php',), ); //postで送られてきたデータ $post_data = $this->input->post('number'); //postデータをもとに$arrayからデータを抽出 $data = $array[$post_data]; //$dataをJSONにして返す $this->output ->set_content_type('application/json') ->set_output(json_encode($data)); } }
クライアント側(ビュー)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Ajaxのサンプル</title> <style></style> <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script> <script> $(function(){ $('button').on('click', function(){ //クリックされたボタンのid属性を取得 var button_id = $(this).attr('id'); //Ajax $.ajax({ type: 'post', // HTTPメソッド(CodeIgniterだとgetは捨てられる) url: 'http://localhost/codeigniter/index.php/ajax', //リクエストの送り先URL(適宜変える) data: {'number': button_id}, //サーバに送るデータ。JSのオブジェクトで書ける dataType: 'json', //サーバからくるデータの形式を指定 //リクエストが成功したらこの関数を実行!! success: function(data){ alert('フレームワーク:' + data.framework + ', 言語:' + data.lang); } }); }); }); </script> </head> <body> <button id="0">ボタン1</button> <button id="1">ボタン2</button> </body> </html>
サーバ側ではAPIを作る感じかな。
あと、ちゃんとモデルに切り分けたいね。