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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化