Jsヘルパーを使ってAjaxしてみる

Twitter ツイート Hatena Bookmark ブックマーク

cakePHPになってからajaxヘルパーからHtmlとJsヘルパーを使う方向になったと思うんですが、なかなか試す機会がなかったです。
ajaxヘルパーすらあまり使っていませんでしたが・・・w

Jsヘルパーつかって普通にAjaxでリストをとってくる場合はこんな間じです。
(※Hogeコントローラのindexメソッドから一覧データを取得してくる場合を想定)
hoge_controller.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class HogeController extends AppController {

	var $name = 'Hoge';
	var $helpers = array('Form', 'Js'=>array('jquery') );

	function index() {
		$this->Hoge->recursive = 0;
		$this->set('hoges', $this->paginate());
	}

	function test() {
	}
}

test.ctp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
	$this->Html->script('jquery',array('inline'=>false));

	$this->Js->get('#btn');
	$request = $this->Js->request(
		array(
			'action' => 'index',
			'controller' => 'hoge'
		),
		array(
			'method' => 'get',
			'sync' => true,
			'update' => '#data',
			'success' => "alert('get data!!!');"
		)
	);
	$this->Js->event('click',$request);
	echo $this->Js->writeBuffer(array('inline'=>false));
?>

<div>
<div id="data"></div>
<input id="btn" type="button" value="取得" />

</div>

意外と気持ちよくかけるなーとおもいますw
ほかにもいろいろなメソッドあるんで、「JqueryEngineHelper」クラスをレビューしてみるとよいかと思います。
ちなみに「jQuery.upload」とか使えるかなーとかおもったんですが、Jsヘルパーじゃ無理っぽいです。やれないことはないと思いますが・・・。

comments powered by Disqus
Built with Hugo
テーマ StackJimmy によって設計されています。