日期:2014-05-16 浏览次数:21387 次
<?php
class SitesController extends AppController
{
public $name = "Sites";
public function ajaxListAll()
{
if ($this->request->is('ajax')) { //这里怎么判断。可能根据情况,但是我使用这样判断是没问题的。
return new CakeResponse(array('body' => json_encode(array('val' => 'test ok')), 'status' => 200));
}
}
}
?>ajaxTest = function(){
$.ajax({
url : '/sites/ajaxListAll',
data : {
name : "test",
shortname : "tst"
},
dataType : 'json',
success : function(html, textStatus) {
alert('Success ' + textStatus + html);
},
error : function(xhr, textStatus, errorThrown) {
alert('An error occurred! ' + errorThrown);
}
});
}<!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>
<title>CakePHP AJAX Demo :: <?php echo $title_for_layout?></title>
<?php echo $this->Html->charset(); ?>
<?php echo $this->Html->script('jquery-1.7.2.min.js'); ?>
</head>
<body>
<div id="container">
<center><h2>CakePHP AJAX Demo</h2></center>
<div id="content"><?php echo $content_for_layout?></div>
<?php
$options = array(
'inline'=>true,
'cache'=>false,
'safe' =>false
);
echo $this->Js->writeBuffer($options);
?>
</div>
</body>
</html> <?php
class AjaxtestController extends AppController {
var $layout = 'ajaxtest'; //指定视图使用的布局为 ajaxtest
var $helpers = array('Html','Js'); //需要用到的视图辅助类
function index(){
}
function hello(){
sleep(1); //本地测试时,为了更好地看到效果,模拟延迟状态
$this->layout = 'ajax'; //此方法为 AJAX 动作,所以布局需要使用 hello.ctp
}
}