为什么Jquery Ajax在Codeigniter3.0.0中使用csrf_protection启用会得到403(禁止)错误?

我正在使用jquery和CodeIgniter3.0.0开发注册但是在我启用csrf_protection为true后我的ajax停止工作。但是如果我禁用csrf_protection为False我的ajax将完美。

这是我的表格

 'POST', 'id' => 'createform')); ?> 

在我完成表单后,我使用Jquery来validation表单字段

  $(document).already(function(){ $("#email").keyup(function () { if ($("#email").val().length >= 0 || $("#email").val() !== '') { ajax_call(); } }); }); function ajax_call() { $.ajax({ type: "post", url: "", // data: $("#createform").serialize(), data: { 'security->get_csrf_token_name(); ?>': 'security->get_csrf_hash(); ?>', email:$("#email").val() }, success: function () { alert("success"); }, dataType: "text", cache: false, success: function (respond) { if ($.trim(respond) === "true") { $("#email-error").css({'display': 'inline', 'font-size': '12px'}); $(".form-error").css({'border': '1px solid red', 'background-color': 'rgba(255, 0, 0, 0.17)', 'color': 'black'}); document.getElementById("csubmit").disabled = true; } else { $("#email-error").css({'display': 'none'}); $(".form-error").css({'border': '', 'background-color': '', 'color': ''}); document.getElementById("csubmit").disabled = false; } } }); }  

通过单击表单元素validation后,我将得到如下图像的错误

在此处输入图像描述

在设置代码进行播放后,我发现每个AJAX调用都会重新生成(更改)CSRF令牌。

因此,第一个按键很好 – 后续的按键会导致post被拒绝,因为您的CSRF令牌不再有效。

快速讨厌修复:你可以做的一件事就是改变

 //$config['csrf_regenerate'] = TRUE; $config['csrf_regenerate'] = FALSE; 

理想情况下,您可以将其设置为TRUE,并在每个post响应上发送回新的令牌。 我正在努力。

CSRF Regenerate = true修复:

处理您希望通过设置允许CSRF令牌在每个Post上重新生成的情况

 $config['csrf_regenerate'] = TRUE; 

你可以这样做…注意:我有一些console.log调试代码 – 你可以删除它。

  

注意:dataType从text更改为json。 此外,我已经硬编码了不可取的令牌名称。 这可以通过多种方式传递(练习对你而言)。

以及account / check_user_existing的测试代码

  public function check_user_existing(){ $new_token = $this->security->get_csrf_hash(); $response = FALSE; if($this->input->post('email') == 'testmy@email.address') { $response = TRUE; } echo json_encode(array('response'=>$response,'token'=>$new_token)); exit(); } 

为了在每个Keyup事件上重新生成CSRF令牌,每个Keyup事件可能有点过分。 但这是另一个问题。