CakePHP中有个Ajax的Helper类,用于处理CakePHP的Ajax功能。由于CakePHP是模仿Ruby on Rails的快速开发框架,所以它也和RoR一样,使用了prototype和scriptaculous来作为它的Ajax库。
下面就几个简单的例子来解析CakePHP 的功能,这次解析基于 http://nio.infor96.com/ajax-in-cakephp/以及http://nio.infor96.com/ajax-in-cakephp-sortable/ 这两篇文章,我对于文章中不对的地方会进行修正。
1、Ajax更新
首先下载scriptaculous库,将js文件放到$cake_dir$/app/webroot/js/scriptaculous/下,然后建立一个模版文件。我取名为my.thtml,放置于$cake_dir$/app/views/layouts/下。
my.thtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CakePHP AJAX Demo :: <?php echo $title_for_layout?></title>
<script src="/js/scriptaculous/prototype.js"></script>
<script src="/js/scriptaculous/scriptaculous.js"></script>
</head>
<body>
<div id="container">
<center><h2>CakePHP AJAX Demo</h2></center>
<div id="content"><?php echo $content_for_layout?></div>
</div>
</body>
</html>
接下来建立controller文件,在$cake_dir$/app/controllers/下面建立index_controller.php文件,源代码如下:
index_controller.php
<?php
class IndexController extends AppController {
var $name = 'Index';
var $uses = array ();
function index() {
}
function hello() {
$this->layout = 'ajax';
}
}
?>
同时建立对应的两个view文件,index.thtml和hello.thtml,放在$cake_dir$/app/views/index/下,对应的源代码如下:
index.thtml
<div id="loading" style="display:none;padding:4px;color:black;background-color:#FAD163;width:100px">
<strong>Loading…</strong>
</div>
<div id="view" style="display:none;background-color:#E8EEF7;padding:4px;border:1px solid silver;width:300px"></div>
<p>
<?php
$options = array(
'update'=>'view',
'loading'=>"Element.hide('view');Element.show('loading')",
'complete'=>"Element.hide('loading');Effect.Appear('view')"
);
echo $ajax->link('Click here!', '/index/hello', $options);
?>
</p>
hello.thtml
<center>Hello, AJAX world!</center>
一切代码准备完毕,访问http://yourhost/index/index的时候就能看到最终效果。但是这不是我想要的结果,必须要清楚scriptaculous是如何在CakePHP中工作的。
查看页面的HTML源代码,找到JS代码段:
<p>
<a href="/index/hello" id="link15098" οnclick="event.returnValue=false; return false;">Click here!</a>
<script type="text/javascript">
Event.observe('link15098', 'click', function(event) {
new Ajax.Updater(
'view',
'/index/hello',
{
asynchronous:true,
evalScripts:true,
onLoading:function(request) {Element.hide('view');Element.show('loading')},
onComplete:function(request) {Element.hide('loading');Effect.Appear('view')},
requestHeaders:['X-Update', 'view']})
},
false
);
</script>
</p>
可以看到CakePHP的AjaxHelper生成了一个a标签和一段JS代码,并为这个a标签加上了事件监听,当你点击这个链接的时候,并不会跳转到href属性里的链接,而是会调用事件监听中定义的函数来进行处理。而在定义的这个监听函数中,我们可以看到生成了一个Ajax.Updater对象,需要更新的标签是id=’view’,请求的URL是’/index/hello’,并且在请求过程中和请求结束时定义了动画事件。
这样一来,只需要弄清楚scriptaculous的工作原理,就算碰到没有CakePHP的情况下,也能够写出具有Ajax功能的程序来。
下次继续写Ajax的AutoComplementation。