在CakePHP 3.4中通过Ajax发送表单并启用了crsf和安全组件 [英] Sending form via ajax in cakephp 3.4 with crsf and security components enabled
问题描述
需要帮助,
我希望能够在App控制器(cakephp 3.4)中启用crsf和安全组件的同时,通过ajax将表单发送至控制器进行处理.我将不胜感激.谢谢
I want to be able to send a form via ajax to a controller for processing while the crsf and security components are enabled in the App controller (cakephp 3.4). Will appreciate any help I can get. Thanks
推荐答案
要发送ajax请求,您需要首先通过docs中指定的head请求发送csrf令牌(
In order to send an ajax request you need to send the csrf token first through the head request as specified in the docs (link)
Cakephp 3.6 +
这是一个 jquery ajax调用
This is an example with a jquery ajax call
$.ajax({
url: '<?php echo $this->Url->build(['controller' => 'Foo', 'action' => 'bar'])?>',
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', '<?php echo $this->request->getParam('_csrfToken') ?>'));
}
});
Cakephp低于3.6
您需要为JavaScript创建或使用Cookie阅读器(例如: js-cookie )
You need to create or use a cookie reader for javascript (like: js-cookie)
这是一个 jquery ajax调用和
This is an example with a jquery ajax call and js-cookie:
$.ajax({
url: '<?php echo $this->Url->build(['controller' => 'Foo', 'action' => 'bar'])?>',
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', Cookies.get('csrfToken'));
}
});
cakephp 3.6发布后更新了答案
这篇关于在CakePHP 3.4中通过Ajax发送表单并启用了crsf和安全组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!