2011-11-26 4 views
0

나는 앵커 속성에서 데이터를 전송하고있어 경우 사용하여 주위에 <form>

<a id="123">foo</a> 

,

jQuery의 $ .post ()를 내 컨트롤러 중 하나에 연결하십시오.

$('.add-fav').click(function() { 
    var id = $(this).attr('id'); 
    $.post('/ajax/addFavorite', function(data){ 
    id : id 
    }, 'json'); 
}); 

컨트롤러 내에서 데이터를 검색하려면 어떻게합니까? 나는 아무것도 검증 할 모델을 사용하지 않기 때문에 Cake의 내장 formhelper 규칙을 사용해서는 안됩니다.

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

     $bar = $_POST['id'] // normally I'd do this to get '123' from the anchor id, but it doesn't work since it wasn't submitted within a form 

     $dataBack = json_encode($bar); 

     if($this->RequestHandler->isAjax()) { 
      if($this->Session->read('Auth.User')) { 
       return $dataBack; 
      } 
     } 
} 

내가 다시 $ .post() 데이터로 json_encoded 연관 배열을 보낼 수 있습니다,하지만 난 원래 (컨트롤러 통과 예를 들어 ID와 다시 보내기) 다시 전송 된 것을 보낼 수없는 것 . 여기에 근본적인 것이 빠져 있거나 입력란에 데이터를 보내지 않으면 불가능합니까 (<form>)?

답변

2

데이터는 ID가 잘 너무 CakePHP의 JS 도우미와 함께 할 수있는 아주 좋은 방법이

$('.add-fav').click(function() { 
    var id = $(this).attr('id'); 
    $.post('/ajax/addFavorite',{id:id}, function(data){ 
    console.log(data); 
    }, 'json'); 
}); 
+0

이제 실제로 제대로 구조화하는 방법을 기억하기 때문에 $ .ajax()를 사용하는 것이 좋습니다. 감사! –

0

$.post의 두 번째 인수로 보내 전달 될 수 있습니다.

$this->Js->get('.add-fav')->event('click', 
     $this->Js->request(
     array(‘controller’ => ‘ajax’, ‘action' => 'addFavorite'), 
      array(
       'data' => 'event.target.id', 
       'async' => true,  
       'dataExpression' => true, 
       'method' => 'POST', 
       //'update' => '#element_id', // to paste the answer of the call 
       //'before' => 'alert("Before request")', 
       //'complete' => 'alert("Callback when request completed")', 
       //'error' => 'alert("Callback for request error")', 
       //'success' => 'alert("Success")', //code to execute if success 
      ) 
     ) 
    ); 
    echo $this->Js->writeBuffer();