CakePHP:Ajax发布请求抛出403错误(权限全部授予)

时间:2019-01-02 11:36:02

标签: php jquery ajax cakephp http-status-code-403

Cakephp项目中的Ajax请求抛出403错误,所有权限均授予localhost(XAMPP)中的项目目录

  

无法加载资源:服务器的响应状态为403   (禁止)/ project / users / saveOrder:1

var request = function() {
            $.ajax({
                beforeSend: function() {
                    messageBox.text('Updating the sort order in the database.');
                },
                complete: function() {
                    messageBox.text('Database has been updated.');
                },
            data: 'sort_order=' + sortInput[0].value + '&ajax=' + submit[0].checked + '&do_submit=1&byajax=1', //need [0]?
            type: 'post',
            url: '/project/users/saveOrder',

        });
        }; 

代码 UsersController:

class UsersController extends AppController
{
    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('saveOrder');
    }

    public function view($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => ['Departments', 'Appointments', 'Roles', 'LeaveRequests', 'TasksTo', 'TasksFrom', 'TasksBy']
        ]); 
        $this->set('user', $user);
    }

    public function change(){
    }
    public function saveOrder() {
        $this->layout = null; 
        if ($this->request->is('post'))
        {

            $ids = explode(",", $this->request->data['priority']); 
            //print_r($ids); die;
            /* run the update query for each id */
            foreach ($ids as $index => $id) {
                if (isset($id) && !empty($id)) {
                    $query = 'UPDATE tasks SET priority = ' . ($index + 1) . ' WHERE id = ' . $id;
                    //$result = mysql_query($query) or die(mysql_error() . ': ' . $query);
                    $data['id'] = $id;
                    $data['priority'] = $index + 1;
                    $this->Task->id = $data['id'];
                    if($this->Task->saveField('priority', $data['priority'])) {
                         echo $query.'<br/>';
                    }else {
                          die('Error, insert query failed');
                    } 
                }
            }
            die;
        }
     }

}

1 个答案:

答案 0 :(得分:1)

您面临此问题,因为您不允许在ajax url中使用正在使用的功能

在您的控制器的beforeFilter()中允许该功能,然后在内部传递功能名称

$this->Auth->allow()

示例

public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('saveOrder');
 }

有关$this->Auth->allow()

的更多想法
$this->Auth->allow(); //Allow all action define in your controller

$this->Auth->allow('editUser'); //Allow only editUser 

$this->Auth->allow(['editUser', 'AddUser']); //Allow only editUser and AddUser

对于cakephp 3

  1. 将其放置在控制器use Cake\Event\Event;顶部
  2. 现在将其添加到过滤器功能

    公共函数beforeFilter(Event $ event) {

    parent::beforeFilter($event);
    $this->Auth->allow('saveOrder');
    

    }