サーチ…


基本的なCakePHP 2.xの例

コントローラ:コントローラでは、RequestHandlerコンポーネントを追加する必要があります。これにより、CakePHPはAjaxリクエストを自動的に検出できるようになります(詳細はhttp://book.cakephp.org/2.0/ja/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>

Cakephp 2.xでのAjaxリクエスト

cakephpでajaxを使うもう一つの方法。 CakephpはAjaxリクエストを提供します。例を見てください。

 $data = $this->Js->get('#id')->serializeForm(array('isForm' => true, 'inline' => true));
//on click send request to controller and displays response data in view
$this->Js->get('#button-id')->event(
        'click', $this->Js->request(
                array('controller' => 'Users', 'action' => 'add'), array(
            'update' => '#time', // field you wish to update
            'data' => $data, // Form Data in serialize form
            'async' => true,    
            'dataExpression'=>true,
            'method' => 'POST' // method get or post
                )
        )
);


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow