doudu8291 2014-11-30 12:16
浏览 67
已采纳

使用jquery ajax发布到CakePHP控制器

I want to post data to a controller in CakePHP, but posting with JQuery always results in"POST http//localhost/SA/myController/editUserData/1 400 (Bad Request)" error and I can't figure out why.

In my view I have the following method, that posts the data to the controller page

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

My controller method looks like this:

  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';
       }
   }

Any ideas??

  • 写回答

1条回答 默认 最新

  • doutao6330 2014-11-30 21:36
    关注

    Two things that may be throwing it.

    (1) Cake's built-in security - so exempt the method from it:

    In AppController.php

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

    (2) Decide how you want your editUserData method to render the view, if you're echo'ing out an 'ok' it will still pull in the default layout and look for an editUserData.ctp in the view (and cause an error if it doesn't find the file), so

    To not render anything, ie a .ctp view file and the default layout.. in the editUserData($id), add

    $this->autoRender = false;
    

    To only render the view file and not the layout:

    $this->autoLayout = false;
    

    ......Then lastly I wound just add this parameter in the ajax call :

    dataType : 'html' // (or JSON?)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法