Jos*_*ejo 1 cakephp cakephp-3.0
我做了一个简单的选择更改。但我有一个问题ang收到以下错误:
Error: [Cake\Http\Exception\InvalidCsrfTokenException] CSRF token mismatch.
Run Code Online (Sandbox Code Playgroud)
这是我在控制器上的功能:
public function municipios() {
$this->viewBuilder()->layout('ajax');
$this->LoadModel('Municipios');
$subregion = $this->request->getData['subregion_id'];
$municipios = $this->Municipios->find('list',[
'limit' => 200,
'conditions' => ['Municipios.subregion_id' => $subregion],
'contain' => ['Subregiones']
]);
$this->set(compact('municipios'));
$this->set('_serialize', 'municipios');
}
Run Code Online (Sandbox Code Playgroud)
这是我的 jquery ajax:
$(document).ready(function () {
$("#subregion-id").bind("change",
function (event) {
$.ajax({
async:true,
data: $("#subregion-id").serialize(),
dataType:"html",
success:
function (data, textStatus) {
$("#municipio-id").html(data);
},
type:"post", url:"\/lavaderos\/municipios"});
return false;
});
});
Run Code Online (Sandbox Code Playgroud)
我阅读了需要令牌的文档,但我不知道该怎么做。
该代码在 3.5.x 中工作正常,但在 3.6.x 中无效
谢谢
您可以通过 ajax 调用中的特殊 X-CSRF-Token 标头向您发送 CSRF 令牌来解决此问题。https://book.cakephp.org/3.0/en/controllers/components/csrf.html
$(document).ready(function () {
$("#subregion-id").bind("change",
function (event) {
$.ajax({
async:true,
data: $("#subregion-id").serialize(),
dataType:"html",
beforeSend: function (xhr) { // Add this line
xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
}, // Add this line
success:function (data, textStatus) {
$("#municipio-id").html(data);
},
type:"post", url:"\/lavaderos\/municipios"});
return false;
});
});
Run Code Online (Sandbox Code Playgroud)
或者
您可以为您的 ajax 操作禁用 CSRF 组件[不推荐 Cakephp],例如:
public function beforeFilter(Event $event) {
if (in_array($this->request->action, ['ajaxEdit'])) {
$this->eventManager()->off($this->Csrf);
}
}
Run Code Online (Sandbox Code Playgroud)