問題描述
需要幫助,
我希望能夠通過 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 發送表單的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!