【问题标题】:Passing data to a CakePHP controller using jQuery's $.post()使用 jQuery 的 $.post() 将数据传递给 CakePHP 控制器
【发布时间】:2012-01-07 02:05:45
【问题描述】:

如果我从锚属性发送数据:

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

周围没有&lt;form&gt;

使用 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;
            }
       }
 }

我可以将一个 json_encoded 关联数组作为数据发送回 $.post(),但我似乎无法将最初发回的内容发送回(例如,通过控制器并将其发回的 id)。我是否在这里遗漏了一些基本的东西,或者如果不在&lt;form&gt; 内的输入字段(可能是隐藏的)中发送数据就不可能吗?

【问题讨论】:

    标签: jquery ajax cakephp post cakephp-1.3


    【解决方案1】:

    CakePHP JS Helper 也有一个很好的方法。

        $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();
    

    【讨论】:

      【解决方案2】:

      要传递的数据作为$.post的第二个参数发送

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

      【讨论】:

      • 现在我知道为什么我喜欢坚持使用 $.ajax(),因为我真的记得如何正确地构建它。谢谢!
      猜你喜欢
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      相关资源
      最近更新 更多