基本 CakePHP 2.x 示例

控制器:在 Controller 中,你必须添加 RequestHandler 组件。这使 CakePHP 能够自动检测 Ajax 请求( 有关详细信息,请参阅: http//book.cakephp.org/2.0/en/core-libraries/components/request-handling.html ):

class YourController extends AppController {
    public $components = array('RequestHandler');
    //...

    public function ajaxCall() {
        if($this->request->is('ajax'){
            // some code that should be executed
            // ...
            // variables you want to return
            $this->set(compact('firstVariable', 'secondVariable'));
            $this->set('_serialize', array('firstVariable', secondVariable))
    }
}

查看代码(使用 jQuery):

<script>
$.ajax({
    type: 'POST',
    url: '/yourController/ajaxCall',
    success: function (result) {
        // result is a JSON array of the returned Variables
    },
    error: function (result){
        console.log(result);
    }
});
</script>