防止表单篡改是安全组件提供的基本功能之一。只要启用它,它就会将所有 POST 视为表单提交。
常规的手动编码 HTML 表单在启用安全组件的情况下无法使用,因此 JQuery 生成的 POST 也无法使用。当然,您可以使用$this->Security->validatePost = false;
or $this->Security->csrfCheck = false;
但随后您就失去了安全组件提供的保护。
为了保持安全组件正常运行,您需要使用 CakePHP 表单助手来创建要通过 ajax 发布的表单。这样一来data[_Token][fields]
and data[_Token][unlocked]
隐藏字段是用它们的键生成的:
<?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 就会成功。
重要的:由于表单助手的令牌只能与安全组件一起使用一次,因此只有当您只想在每个页面生成时 POST 一次时,此解决方案才有效。如果您需要能够在页面重新加载之间多次发布相同的表单,那么当您在控制器的开头添加安全组件时,您需要执行以下操作:
public $components = array(
'Security' => array(
'csrfUseOnce' => false
)
);
...这将允许令牌用于多个请求。它不是as安全,但你可以将它与csrfExpires
以便令牌最终会过期。这一切都记录在Cake书的CSRF配置部分 http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#csrf-configuration.