【发布时间】:2017-01-25 17:28:22
【问题描述】:
我刚刚开始使用 codeigniter 我想通过 ajax 将一些数据插入数据库,但是我的 ajax 调用有问题;
我一直在寻找两个小时,但我无法解决问题。
我的问题是当我点击提交按钮时,它说禁止。
我的 csrf 保护也设置为 TRUE!请帮忙,谢谢
JS
$(document).ready(function() {
$(".addbtn").click(function (e) {
e.preventDefault();
if($("#mname").val()==='' ||
$('#sname').val() === '' ||
$('#genre').val()==='' ||
$('#album').val()==='' ||
$('#publishyear').val() ==='' ||
$('#artist').val()==='')
{
alert("Please fill all the fields!");
return false;
}
$("#FormSubmit").hide();
$("#LoadingImage").show();
var baseurl = "<?php echo base_url(); ?>";
var data = {
'mname': $("#mname").val(),
'sname': $('#sname').val(),
'genre': $('#genre').val(),
'album': $('#album').val(),
'publishyear': $('#publishyear').val(),
'artist': $('#artist').val(),
'<?php echo $this->security->get_csrf_token_name(); ?>':
'<?php echo $this->security->get_csrf_hash(); ?>'
};
$.ajax({
type: "POST",
url: baseurl+"index.php/admin_page/send_ajax",
data: data,
success:function(){
alert("success");
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show();
$("#LoadingImage").hide();
alert(thrownError);
}
});
});});
配置文件
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
控制器
public function send_ajax(){
$data = array(
'name_of_music'=>$this->input->post("mname", TRUE),
'artist'=>$this->input->post("artist", TRUE),
'name_of_singer'=>$this->input->post("sname", TRUE),
'genre'=>$this->input->post("genre", TRUE),
'album'=>$this->input->post("album", TRUE),
'publishyear'=>$this->input->post("publishyear", TRUE)
);
$json_data['lyrics_info_data'] = json_decode($data);
$this->user_model->insert_json_in_db($json_data);
}
型号
public function insert_json_in_db($json_data){
$this->db->insert('lyrics', $json_data);
}
【问题讨论】:
-
你应该
json_encode($data),而不是json_decode -
Zeeshan 我修好了,但还是不行!说禁止
-
你能通过输入
echo 'In controller;exit;来确定你的控制器的函数是否被ajax调用 -
是的,我确定。一切都设置正确!我不知道为什么还要说禁止
-
我觉得问题是csrf配置我不知道在哪里!
标签: ajax codeigniter csrf