Sending form via ajax in cakephp 3.4 with crsf and security components enabled(在启用 crsf 和安全组件的 cakephp 3.4 中通过 ajax 发送表单)
问题描述
需要帮助,
我希望能够通过 ajax 将表单发送到控制器进行处理,同时在 App 控制器 (cakephp 3.4) 中启用 crsf 和安全组件.将不胜感激我能得到的任何帮助.谢谢
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 请求,您需要首先通过文档中指定的头部请求发送 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 调用和 js-cookie:
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 发布后更新答案
这篇关于在启用 crsf 和安全组件的 cakephp 3.4 中通过 ajax 发送表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在启用 crsf 和安全组件的 cakephp 3.4 中通过 ajax 发
基础教程推荐
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何替换eregi() 2022-01-01
