【发布时间】:2018-05-09 16:50:03
【问题描述】:
您好,我在我的 codeigniter 框架中将 CSRF 保护设置为 true,我想知道如何在我的 AJAX 请求中应用 CSRF 令牌,因为我收到 The action you requested is not allowed 是我的 AJAX 请求 , 这是我正在处理的代码示例:
HTML
<button type="button"
class="btn btn-primary btn-sm edit_category"
data-id="<?= $category->category_id ?>">
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
</button>
当用户点击这个 JS 运行的按钮时:
$(document).on('click', '.edit_category', function() {
$.ajax({
type: 'POST',
url: base_url + 'admin/getinfo_category',
data: {
'category_id': $(this).data('id')
},
success:function(data){
console.log( JSON.parse(data) );
},
error: function (data) {
console.log('ajax error');
} // end of error
}); // ajax
});
控制器
public function getinfo_category() {
if( ($this->session->userdata('logged_in') && $this->session->userdata('role') ) &&
($this->session->userdata('logged_in') == TRUE && $this->session->userdata('role') == 'admin' ) ) {
$query = $this->admin_model->getinfo_category($this->input->post('category_id'));
if( isset($query) ) {
echo json_encode($query);
} else {
echo 'ajax fail';
}
} else {
redirect(base_url() . 'admin/index');
}
}
型号
public function getinfo_category($category_id) {
$query = $this->db->select('category_name, category_desc')->where('category_id', $category_id)->get('category');
if($query) {
return $query->row();
} else {
return false;
}
}
现在它应该做的是从基于 $category_id 的数据库中获取数据,然后在控制台上输出结果。
编辑
很抱歉,我仍然收到错误提示
【问题讨论】:
标签: javascript php jquery ajax codeigniter