【问题标题】:Posting to CakePHP controller using jquery ajax使用 jquery ajax 发布到 CakePHP 控制器
【发布时间】:2015-01-28 13:22:51
【问题描述】:

我想将数据发布到 CakePHP 中的控制器,但使用 JQuery 发布总是会导致“POST http//localhost/SA/myController/editUserData/1 400 (Bad Request)”错误,我不知道为什么.

在我看来,我有以下方法,将数据发布到控制器页面

   $scope.saveUser = function() {
    $.ajax({
        type: 'POST',
        url: '<?php echo Router::url(array(
                                        'controller' => 'myController',
                                        'action' => 'editUserData',
                                        0 => $userInfo['user']['id'],));?>',
        data: { email: 'cabraham@delhi.k12'},//"my edited data for example"
        success: function (data) {
          alert(data);
        }
    });

我的控制器方法如下所示:

  public function editUserData($id) {
       if($this->request->is('post') || $this->request->is('put')) {
           $this->AcsaUser->save($this->request->data('email'));//edit and save the new data
           echo 'ok';
       }
   }

有什么想法吗??

【问题讨论】:

  • 路由器的“0”键太奇怪了。为什么不是“身份证”?并将 dataType 属性设置为 ajax 对象。
  • @Alex 不是 that 奇怪,但没有必要,它可以在没有明确指定键的情况下正常工作,使用像 id 这样的命名键但是不会像这样工作表示一个命名元素,这不会匹配可能的路由并生成类似/id:1的URL。
  • saving data from jquery的可能重复

标签: php jquery ajax cakephp


【解决方案1】:

有两件事可能会抛出它。

(1) Cake 的内置安全性 - 所以免除它的方法:

在 AppController.php 中

public function beforeFilter() {
    $this->Security->unlockedActions = array('editUserData')
}

(2) 决定您希望您的 editUserData 方法如何呈现视图,如果您回显“ok”,它仍将拉入默认布局并在视图中查找 editUserData.ctp(和如果找不到文件会导致错误),所以

要不渲染任何东西,即.ctp 视图文件和默认布局.. 在editUserData($id) 中,添加

$this->autoRender = false;

只渲染视图文件而不渲染布局:

$this->autoLayout = false;

......最后我只是在ajax调用中添加了这个参数:

dataType : 'html' // (or JSON?)

【讨论】:

  • 感谢@david.philip,问题出在布局中,我按照您在第 2 点中的建议解决了问题,但是这一行 $this->AcsaUser->save($this->request->数据('电子邮件'));仍然没有工作,你有什么想法吗?或者我应该如何编辑我的数据?
  • 很高兴你来对了!因此,假设在 myController 中加载了“AcsaUser”模型,请设置模型 ID 以进行更新:$this->AcsaUser->id = $id; 然后按原样保存它,也在你的ajax中,你如何拥有它并没有错,但是将它作为=> url : 'Html->url(array('controller' => 'myController ', '动作' => 'editUserData',$id)); ?>';
  • 是的,谢谢 :) 问题在于设置 ID。此行解决了问题 $this->AcsaUser->id = $id;
猜你喜欢
  • 1970-01-01
  • 2013-05-14
  • 1970-01-01
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
  • 2016-12-07
  • 2017-12-09
  • 2014-03-01
相关资源
最近更新 更多