我正在尝试使用 ajax post 来执行操作。 GET 请求工作正常,但是当我尝试 POST 时,我在 firebug 中看到“400 错误请求”,并且 View 返回“黑洞”响应。
这是 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 的安全设置还是我在这里缺少什么?
最佳答案
防止表单篡改是安全组件提供的基本功能之一。只要启用它,它就会将所有 POST 视为表单提交。
常规的手动编码 HTML 表单在启用安全组件的情况下无法工作,因此 JQuery 生成的 POST 也无法工作。当然,您可以使用 $this->Security->validatePost = false;
或 $this->Security->csrfCheck = false;
但随后您就会失去保护安全组件提供的。
为了保持安全组件正常运行,您需要使用 CakePHP 表单助手来创建要通过 ajax 发布的表单。这样,data[_Token][fields]
和 data[_Token][unlocked]
隐藏字段将使用其 key 生成:
<?php
echo $this->Form->create('Test',array('id'=>'testform'));
echo $this->Form->input('Something');
echo $this->Form->submit();
echo $this->Form->end();
?>
这将生成如下内容:
<form action="/your/url" id="testform" method="post" accept-charset="utf-8">
<div style="display:none;">
<input type="hidden" name="_method" value="POST"/>
<input type="hidden" name="data[_Token][key]" value="9704aa0281d8b5a2fcf628e9fe6f6c8410d8f07a" id="Token937294161"/>
</div>
<div class="input text">
<input name="data[Test][Something]" class="required" type="text" id="TestSomething"/>
</div>
<div class="submit">
<input type="submit" />
</div>
<div style="display:none;">
<input type="hidden" name="data[_Token][fields]" value="0c81fda1883cf8f8b8ab39eb15d355eabcfee7a9%3A" id="TokenFields817327064"/>
<input type="hidden" name="data[_Token][unlocked]" value="" id="TokenUnlocked281911782"/>
</div>
</form>
现在只需在 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 就会成功。
重要提示:由于表单助手的 token 只能与安全组件一起使用一次,因此只有当您只想在每个页面生成时 POST 一次时,此解决方案才有效。如果您需要能够在页面重新加载之间多次发布相同的表单,那么当您在 Controller 的开头添加安全组件时,您需要执行以下操作:
public $components = array(
'Security' => array(
'csrfUseOnce' => false
)
);
...这将允许 token 用于多个请求。它并不安全,但您可以将其与 csrfExpires 结合使用,以便 token 最终会过期。这全部记录在 CSRF configuration section of the Cake book 中.
关于jquery - CakePHP ajax 帖子不断返回 400 Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10624311/