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?)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?