0

私は CakePHP が初めてで、CakePHP ビューからコントローラー内の関数への非同期呼び出しを行う方法を理解しようとしています。コントローラー関数が文字列を返し、ビューにこの文字列を表示させたいと思います。また、ヘルパーを使用せずにこれを行いたいと思います。私はウェブ上で例を見つけようとしてきましたが、そうすることができませんでした。誰にも簡単な例がありますか?jQueryも使用しています。

ありがとう

4

1 に答える 1

3

CakePHP には、aJax 関数の作成を支援する組み込みの JS ヘルパーがあります。唯一の問題は、頭に jquery を含めることです。そうしないと、ケーキで jQuery エラーがスローされます。詳細はこちらhttp://book.cakephp.org/2.0/en/core-libraries/helpers/js.html

あなたのフォーム:

<?php 
  echo $this->Form->create('User', array('default'=>false, 'id'=>'YourForm'));
  echo $this->Form->input('username');
  echo $this->Form->submit('Check Username');
  echo $this->Form->end();
?>

Ajax 関数: ('update'=>'#na') は、ビューで更新する要素の ID です。

<?php
  $data = $this->Js->get('#YourForm')->serializeForm(array('isForm' => true, 'inline' => true));
  $this->Js->get('#YourForm')->event(
    'submit',
    $this->Js->request(
      array('action' => 'checkUsername', 'controller' => 'user'),
      array(
        'update' => '#na',
        'data' => $data,
        'async' => true,    
        'dataExpression'=>true,
        'method' => 'POST'
      )
    )
  );
  echo $this->Js->writeBuffer();                                                 
?>

ユーザーコントローラーの機能

function checkUsername(){
  $this->autoRender = false;

  $username = $this->User->find('first', array('conditions'=>array('User.username'=>$this->request->data['User']['username'])));

  if ( $username == true ) 
    echo 'Username is taken';
  else
    echo 'Username is not taken';  
}

編集* * *これを行うために CakePHP ヘルパーではなく jQuery を使用したい場合は、aJax を使用してアクションを呼び出し、以下のように要素を更新します*

$('#element').on('click', function() {
  $.ajax({
      url : '/controller/action',
      type: 'POST',
      success : function(response){
        $('#elementToUpdate').html(response);
      }
  });

} });

コントローラーアクションでは、ビューに表示したい「文字列」を返すことができます

function action(){
  $string = 'Show this in the view';

   return $string;
}

上記の例は、id が「element」の要素を「クリック」すると実行され、「成功」すると、id が「elementToUpdate」の要素が文字列「Show this in the view」に変更されます。コントローラーアクション。

于 2013-10-21T15:26:12.000 に答える