我遇到一个错误,它说“ DataTables警告:表id = table-Ajax错误。有关此错误的更多信息,请参见this line”。之后,我检查了元素,并出现1错误并说“无法加载资源:服务器响应状态为404(未找到)”
控制器:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class section_controller extends CI_Controller{
public function __construct()
{
parent:: __construct();
$this->load->model('section_model','section');
}
public function index()
{
$this->load->helper('url');
$this->load->view('section_view');
}
public function ajax_list()
{
$list = $this->section_model->get_datatables();
$data = array();
$no = $_POST['start'];
foreach($list as $section) {
$no++;
$row = array();
$row[] = $section->sec_ID;
$row[] = $section->secname;
$row[] = $section->sec;
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)"
title="Edit" onclick="edit_section('."'".$section->sec_ID."'".')"><i
class="glyphicon glyphicon-pencil"></i> Edit</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->section->count_all(),
"recordsFiltered" => $this->section->count_filtered(),
"data" => $data,
);
echo json_encode($output);
}
public function ajax_edit($sec_ID)
{
$data = $this->section->get_by_id($sec_ID);
echo json_encode($data);
}
public function ajax_add()
{
$this->_validate();
$data = array(
'sec_ID' => $this->input->post('sec_ID'),
'secname' => $this->input->post('secname'),
'sec' => $this->input->post('sec'),
);
$insert = $this->section->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'sec_ID' => $this->input->post('sec_ID'),
'secname' => $this->input->post('secname'),
'sec' => $this->input->post('sec'),
);
$this->section->update(array('sec_ID' => $this->input->post('sec_ID')),
$data);
echo json_encode(array("status" => TRUE));
}
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('sec_ID') == '')
{
$data['inputerror'][] = 'sec_ID';
$data['error_string'][] = 'ID is required';
$data['status'] = FALSE;
}
if($this->input->post('secname') == '')
{
$data['inputerror'][] = 'secname';
$data['error_string'][] = 'Section name is required';
$data['status'] = FALSE;
}
if($this->input->post('sec') == '')
{
$data['inputerror'][] = 'dob';
$data['error_string'][] = 'Section is required';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
}
?>
型号:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class section_model extends CI_Model{
var $table = 'section';
var $column_order = array('sec_ID','secname','sec',null);
var $column_search = array('secname','sec');
var $order = array('sec_ID'=>'desc');
public function __construct()
{
parent::__construct();
$this->load->database();
}
private function _get_datatables_query()
{
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with
OR clause better with bracket. because maybe can combine with
other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$this->db->order_by($this->column_order[$_POST['order']['0']
['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
public function get_by_id($sec_ID)
{
$this->db->from($this->table);
$this->db->where('sec_ID',$sec_ID);
$query = $this->db->get();
return $query->row();
}
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
}
?>
视图:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sections</title>
<link rel="stylesheet" href="<?php echo
base_url('assets/bootstrap/css/bootstrap.min.css')?>">
<link rel="stylesheet" href="<?php echo
base_url('assets/datatables/css/jquery.dataTables.min.css')?>">
</head>
<body>
<br>
<div class="container">
<h1>Sections</h1>
<br>
<button class="btn btn-success" onclick="add_section()"><i
class="glyphicon glyphicon-plus"></i> Add Section</button>
<button class="btn btn-default" onclick="reload_table()"><i
class="glyphicon glyphicon-refresh"></i> Reload</button><br><br>
<table id="table" class="table table-striped table-bordered"
cellspacing="0" width="100%">
<thead>
<tr>
<th>Section ID</th>
<th>Section Name</th>
<th>Section</th>
<th>Actions</th>
</thead>
<tbody></tbody>
<tfoot>
<tr>
<th>Section ID</th>
<th>Section Name</th>
<th>Section</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
</div>
<script src="<?php echo base_url('assets/jquery/jquery-3.3.1.min.js')?>">
</script>
<script src="<?php echo base_url('assets/bootstrap/js/bootstrap.min.js')?>">
</script>
<script src="<?php echo
base_url('assets/datatables/js/jquery.dataTables.min.js')?>"></script>
<script src="<?php echo
base_url('assets/datatables/js/dataTables.bootstrap.js')?>"></script>
<script type="text/javascript">
var save_method;
var table;
$(document).ready(function(){
table = $('#table').DataTable({
"processing": true,
"serverside": true,
"order": [],
"ajax": {
"url": "<?php echo site_url('section_controller/ajax_list')?
>",
"type": "POST"
},
"columnDefs":[
{
"targets": [-1],
"orderable": false,
},
],
});
$("input").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
function add_section()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Section'); // Set Title to Bootstrap
modal title
}
function edit_section(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('section_controller/ajax_edit/')?
>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="sec_ID"]').val(data.sec_ID);
$('[name="secname"]').val(data.secname);
$('[name="sec"]').val(data.sec);
$('#modal_form').modal('show'); // show bootstrap modal
when complete loaded
$('.modal-title').text('Edit Section'); // Set title to
Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table()
{
table.ajax.reload(null,false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('section_controller/ajax_add')?>";
} else {
url = "<?php echo site_url('section_controller/ajax_update')?
>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax
table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i <
data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-
error'); //select parent twice to select div form-group class and
add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
//select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / updating data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
});
</script>
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Section Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Section
ID</label>
<div class="col-md-9">
<input name="sec_ID" placeholder="Section ID"
class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Section
Name</label>
<div class="col-md-9">
<input name="secname" placeholder="Section Name"
class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Section</label>
<div class="col-md-9">
<input name="sec" placeholder="Section"
class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn
btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-
dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</body>
</html>
我正在将codeigniter与数据表,jquery和bootstrap插件一起使用。