基本 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>