问题在于 csrf 令牌仅对一次调用有效,因此如果您想在另一个发布请求上使用 ajax 而不刷新页面,您需要以某种方式获取新令牌而不重新加载表单。您可以在您的 codeigniter 控制器中通过将新令牌发送回请求脚本来执行此操作。
在您的 CodeIgniter 控制器中:
$data = array('data'=> 'data to send back to browser');
$csrf = $this->security->get_csrf_hash();
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('data' => $data, 'csrf' => $csrf)));
$data = 返回给浏览器的数据
$csrf = 浏览器用于下一个 ajax 发布请求的新 csrf 令牌
显然,您可以通过其他方式输出它,但 JSON 主要用于 ajax 调用。还要在每个发布响应中以这种方式包含令牌,以用于下一个发布请求
然后在你的下一个 ajax 请求(javascript)中:
var token = data.csrf;
$.ajax({
url: '/next/ajax/request/url',
type: 'POST',
data: { new_data: 'new data to send via post', csrf_token:token },
cache: false,
success: function(data, textStatus, jqXHR) {
// Get new csrf token for next ajax post
var new_csrf_token = data.csrf
//Do something with data returned from post request
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle errors here
console.log('ERRORS: ' + textStatus + ' - ' + errorThrown );
}
});
还请记住,我在哪里找到了 csrf_token:token,将 crf_token 替换为您在 application/config/config.php 中找到的令牌的名称,上面写着 $config['csrf_token_name'] = 'csrf_token';