CakePHP ajaxpost不断返回400 Bad Request
我想在动作中使用ajaxpost。 GET请求工作正常但是当我尝试POST时,我在firebug中看到’400 Bad Request’并且视图返回’Black hole’响应。
这是Jquery请求:
$.ajax({ url:"/usermgmt/users/editUser", type:"POST", success:function(data) { alert('Wow this actually worked'); //ko.applyBindings(self); }, error:function() { alert('This will never work'); } });
这是由于Cake的安全设置还是我在这里缺少的?
防止forms篡改是安全组件提供的基本function之一。 只要它已启用,它就会将所有POST视为表单提交。
常规的手工编码HTML表单不能与启用的安全组件一起使用,因此JQuery生成的POST也不会。 当然,您可以使用$this->Security->validatePost = false;
或$this->Security->csrfCheck = false;
但是你失去了安全组件提供的保护。
要使安全组件保持正常运行,您需要使用CakePHP表单助手创建您要通过ajax发布的表单。 这样, data[_Token][fields]
和data[_Token][unlocked]
隐藏字段将使用其键生成:
Form->create('Test',array('id'=>'testform')); echo $this->Form->input('Something'); echo $this->Form->submit(); echo $this->Form->end(); ?>
这将生成如下内容:
现在只需要在JQuery中序列化这个表单,就可以使用ajax POST发送它:
$('#testform').submit(function(event) { $.ajax({ type: 'POST', url: "/your/url", data: $('#testform').serialize(), success: function(data){ alert('Wow this actually worked'); }, error:function() { alert('This will never work'); } }); event.preventDefault(); // Stops form being submitted in traditional way });
现在,如果按下提交按钮,POST将成功。
重要提示:由于表单助手的令牌只能与安全组件一起使用,因此只有每打算生成一次POST时,此解决方案才有效。 如果您需要能够在页面重新加载之间多次发布相同的表单,那么当您在Controller的开头添加安全组件时,您需要执行以下操作:
public $components = array( 'Security' => array( 'csrfUseOnce' => false ) );
…这将允许令牌用于多个请求。 它不那么安全,但您可以将它与csrfExpires
结合使用,以便令牌最终到期。 这一切都记录在Cake书的CSRF配置部分 。
仅供参考,CakePHP 2.3及更高版本现在包含unlockedActions,仅用于控制器或AppController中的beforeFilter。
$this->Security->unlockedActions = array('ajaxAction');
来自: http : //book.cakephp.org/2.0/en/core-libraries/components/security-component.html#disabling-security-component-for-specific-actions
让shure你把函数editUser放在:
public function beforeFilter(){ parent::beforeFilter() $this->Auth->allow('editUser'); }
在UsersController中,
问候
约瑟夫的答案对我来说遗漏了一个细节。 我的表单和ajax调用是在index.ctp中调用/controller/edit.ctp所以我的$ this-> Form-> create call需要添加’action’=>’/ controller / edit’。