adminlte中数据表格datatable.js中的完整使用方法小案例
想必做过后端的人对数据表格都很熟系,可以说不可缺少,今天就给大家介绍一下用,基本用法,请复制第一个php和js文件,直接复制就可以使用
,后面还有一个完整的,但是有的外部链接没找到,所以先和大家说一下最基本的表格,好了,请复制下看效果吧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AdminLTE 3 | DataTables</title>
<!--第一步:引入Javascript / CSS (CDN)-->
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css"
href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/dataTables.bootstrap4.min.css">
<style>
html,
body {
padding: 30px;
}
.selected {
background-color: rgb(230, 222, 115) !important;
}
</style>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
<div class="content">
<table id="example" class="table table-striped table-bordered table-hover" style="width:100%">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Position</th>
<th>Office</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
</table>
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap4.min.js"></script>
<script>
var timer = null; //延时搜索,
var timeout = 1000; // 当在搜索时,只有超过间隔时间(1000)才开始搜索
var url = "./demo.php" //请求地址
var table = null; //表格
var request = (url, params, method = "GET") => {
return new Promise((resolve, reject) => {
$.ajax({
type: method,
url: url,
cache: false, //禁用缓存
data: params, //传入组装的参数
dataType: "json",
success: function (result) {
resolve(result);
},
error: function () {
reject('出错')
}
});
})
}
// 修改
function update(me) {
var row = table.rows($(me).parents('tr')).data()[0]; // 选中行数的数据
alert('修改:' + JSON.stringify(row))
}
// 删除
async function del(me) {
var row = table.rows($(me).parents('tr')).data()[0]; // 选中行数的数据
var { first_name } = row; //这里一般是主键,但是没有传过来的id值,这里就用name替代了
var param = {
first_name,
method: 'del'
}; //传递的参数,也可以在添加一些判断条件
var res = await request('./demo.php', param);
if (res && res.code == 0) { //判断返回的数据
// 这个方法不会调用表格刷新,但是根据判断,已经删除了,所有直接js删除
// table.row('.selected').remove().draw( false );//官网方法,但是我还是喜欢自己的方法,为什么,因为刷新花时间
$(me).parents('tr').remove();
alert('删除成功')
}
}
$(document).ready(function () {
table = $('#example').DataTable({
"processing": true,
"serverSide": true,
ajax: function (data, callback, settings) {
// data - 发送到服务器的参数
// callback - 回调函数 服务器回传的集合应该传给这个回调函数,作为其参数
// settings - DT的配置对象。
// console.log(data);
if (data.search.value.trim() != '') { //如果搜索不为空,即点击搜索,但不能时时刷新,需要有一段是时间不操作才刷新
clearTimeout(timer)
timer = setTimeout(function () {
request(url, data).then(result => {
callback(result);
})
}, timeout)
} else {
request(url, data).then(result => {
callback(result);
})
}
},
// 上面ajax等同于 "ajax": "./demo.html",
"columns": [{
'sTitle': '第一个名字', //在thead中显示,有过原来有thead则替换
"data": "first_name",
"width": '20%',
'render': function (data, type, row) {
// console.log(data); //当前字段的内容
// console.log(type);// 数据类型 - 有这些值:filter、display、type、sort
// console.log(row); //当前这条数据的所有内容,整个row的数据
return "<span style='color:red'>" + data + '</span>';
},
'class': 'text-center', //添加一个css
"orderable": false //此字段不排序,需要注意,前提是不能指定 即下面的order,(默认指定)
},
{ "data": "last_name", },
{ "data": "position" },
{ "data": "office" },
{ "data": "start_date" },
{
'render': function (data, type, row) {
return `
<button type="button" class="btn btn-sm btn-info" οnclick="update(this)">修改</>
<button type="button" class="btn btn-sm btn-danger " οnclick="del(this)">删除</button>
`;
},
}
],
columnDefs: [{
'targets': [1, 2, 3, 4],
// 'orderable': false// 和 "orderable": false一样,对已经设置了order属性的无效.234为下标
}],
"language": //把文字变为中文
{
"sProcessing": "加载中...",
"sLengthMenu": "显示条数: _MENU_ ",
"sZeroRecords": "没有匹配结果",
"sInfo": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项",
"sInfoEmpty": "显示第 0 至 0 项结果,共 0 项",
"sInfoFiltered": "(由 _MAX_ 项结果过滤)",
"sInfoPostFix": "",
"sSearch": "搜索:",
"sUrl": "",
"sEmptyTable": "表中数据为空",
"sLoadingRecords": "载入中...",
"sInfoThousands": ",",
"oPaginate": {
"sFirst": "《", //首页
"sPrevious": "<", //上一页
"sNext": ">", //下一页
"sLast": "》" //尾页
},
},
"pagingType": "full_numbers", //显示首页尾页
'aLengthMenu': [3, 10, 20, 30], //设置每页显示记录的下拉菜单
'bFilter': true, //搜索栏
'order': [
[1, 'desc'],
[2, 'asc'],
], //指定排序,默认0 asc
// 'ordering' : false, 禁止排序
// "buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"]
})
$('#example').
on('order.dt', function () {
console.log('排序');
}).
on('search.dt', function () {
console.log('搜索');
}).
on('page.dt', function () {
console.log('翻页');
}).dataTable();
});
</script>
</body>
</html>
php
<?php
// 请求的数据格式
$data = [
"draw" => $_GET['draw'],
"recordsTotal" => 570,//记录总数
"recordsFiltered" => 60,//过滤后的总记录数
'get' => $_GET, //ajax get提交过来的参数,无用,但方便自己观看
"data" => [["first_name" => "Airi", "last_name" => "Satou", "position" => "Accountant", "office" => "Tokyo", "start_date" => "28th Nov 08", "salary" => "$162,700",], ["first_name" => "Angelica", "last_name" => "Ramos", "position" => "Chief Executive Officer (CEO)", "office" => "London", "start_date" => "9th Oct 09", "salary" => "$1,200,000"], ["first_name" => "Ashton", "last_name" => "Cox", "position" => "Junior Technical Author", "office" => "San Francisco", "start_date" => "12th Jan 09", "salary" => "$86,000"],]
];
$data1 = [
"draw" => $_GET['draw'],
"recordsTotal" => 570,
"recordsFiltered" => 60,
'get' => $_GET, //ajax get提交过来的参数,无用,但方便自己观看
"data" => [["first_name" => "Airi", "last_name" => "Satou", "position" => "Accountant", "office" => "Tokyo", "start_date" => "28th Nov 08", "salary" => "$162,700",], ["first_name" => "Angelica", "last_name" => "Ramos", "position" => "Chief Executive Officer (CEO)", "office" => "London", "start_date" => "9th Oct 09", "salary" => "$1,200,000"], ["first_name" => "Ashton", "last_name" => "Cox", "position" => "Junior Technical Author", "office" => "San Francisco", "start_date" => "12th Jan 09", "salary" => "$86,000"], ["first_name" => "Airi", "last_name" => "Satou", "position" => "Accountant", "office" => "Tokyo", "start_date" => "28th Nov 08", "salary" => "$162,700",], ["first_name" => "Angelica", "last_name" => "Ramos", "position" => "Chief Executive Officer (CEO)", "office" => "London", "start_date" => "9th Oct 09", "salary" => "$1,200,000"], ["first_name" => "Ashton", "last_name" => "Cox", "position" => "Junior Technical Author", "office" => "San Francisco", "start_date" => "12th Jan 09", "salary" => "$86,000"], ["first_name" => "Airi", "last_name" => "Satou", "position" => "Accountant", "office" => "Tokyo", "start_date" => "28th Nov 08", "salary" => "$162,700",], ["first_name" => "Angelica", "last_name" => "Ramos", "position" => "Chief Executive Officer (CEO)", "office" => "London", "start_date" => "9th Oct 09", "salary" => "$1,200,000"], ["first_name" => "Ashton", "last_name" => "Cox", "position" => "Junior Technical Author", "office" => "San Francisco", "start_date" => "12th Jan 09", "salary" => "$86,000"], ["first_name" => "Airi", "last_name" => "Satou", "position" => "Accountant", "office" => "Tokyo", "start_date" => "28th Nov 08", "salary" => "$162,700",], ["first_name" => "Angelica", "last_name" => "Ramos", "position" => "Chief Executive Officer (CEO)", "office" => "London", "start_date" => "9th Oct 09", "salary" => "$1,200,000"], ["first_name" => "Ashton", "last_name" => "Cox", "position" => "Junior Technical Author", "office" => "San Francisco", "start_date" => "12th Jan 09", "salary" => "$86,000"], ["first_name" => "Airi", "last_name" => "Satou", "position" => "Accountant", "office" => "Tokyo", "start_date" => "28th Nov 08", "salary" => "$162,700",], ["first_name" => "Angelica", "last_name" => "Ramos", "position" => "Chief Executive Officer (CEO)", "office" => "London", "start_date" => "9th Oct 09", "salary" => "$1,200,000"], ["first_name" => "Ashton", "last_name" => "Cox", "position" => "Junior Technical Author", "office" => "San Francisco", "start_date" => "12th Jan 09", "salary" => "$86,000"],]
];
$del = [
"code" => 0,
'msg' => "删除成功",
'data' => []
];
if ($_GET['length'] == 3) {
echo json_encode($data, true);
} elseif($_GET['method'] == 'del'){
echo json_encode($del, true);
} else {
echo json_encode($data1, true);
}
简化版js
原先的注释太多,如果我自己用的话,还要在修改,所以干脆,自己吧最基本的修改出来,可能修改的表如下
- 修改js开头var中的变量
- columns中的内容,字段不同,内容自然不同
- language 修改各种汉字,原先全英文
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>数据表格</title>
<link rel="stylesheet" type="text/css"
href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/dataTables.bootstrap4.min.css">
<style>
html,
body {
padding: 30px;
}
.selected {
background-color: rgb(230, 222, 115) !important;
}
</style>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
<div class="content">
<table id="example" class="table table-striped table-bordered table-hover" style="width:100%">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Position</th>
<th>Office</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
</table>
</div>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap4.min.js"></script>
<script>
var timer = null; //延时搜索,
var timeout = 1000; // 当在搜索时,只有超过间隔时间(1000)才开始搜索
var url = "./demo.php" //请求地址
var delurl = "./demo.php" //请求地址
var table = null; //表格
var request = (url, params, method = "GET") => {
return new Promise((resolve, reject) => {
$.ajax({
type: method,
url: url,
cache: false, //禁用缓存
data: params, //传入组装的参数
dataType: "json",
success: function (result) {
resolve(result);
},
error: function () {
reject('出错')
}
});
})
}
// 修改
function update(me) {
var row = table.rows($(me).parents('tr')).data()[0]; // 选中行数的数据
alert('修改:' + JSON.stringify(row))
}
// 删除
async function del(me) {
var row = table.rows($(me).parents('tr')).data()[0]; // 选中行数的数据
var { first_name } = row; //这里一般是主键,但是没有传过来的id值,这里就用name替代了
var param = { first_name, method: 'del' }; //传递的参数,也可以在添加一些判断条件
var res = await request(delurl, param);
if (res && res.code == 0) { //判断返回的数据
$(me).parents('tr').remove();
alert('删除成功')
}
}
$(document).ready(function () {
table = $('#example').DataTable({
"processing": true,
"serverSide": true,
ajax: function (data, callback, settings) {
if (data.search.value.trim() != '') { //如果搜索不为空,即点击搜索,但不能时时刷新,需要有一段是时间不操作才刷新
clearTimeout(timer)
timer = setTimeout(function () {
request(url, data).then(result => {
callback(result);
})
}, timeout)
} else {
request(url, data).then(result => {
callback(result);
})
}
},
"columns": [{
'sTitle': '第一个名字', //在thead中显示,有过原来有thead则替换
"data": "first_name",
"width": '20%',
'render': function (data, type, row) {
return "<span style='color:red'>" + data + '</span>';
},
'class': 'text-center', //添加一个css
},
{ "data": "last_name", "orderable": false },
{ "data": "position" , "orderable": false},
{ "data": "office", "orderable": false },
{ "data": "start_date","orderable": false },
{"orderable": false ,
'render': function (data, type, row) {
return `
<button type="button" class="btn btn-sm btn-info" οnclick="update(this)">修改</>
<button type="button" class="btn btn-sm btn-danger " οnclick="del(this)">删除</button>
`;
},
}
],
"language": //把文字变为中文
{
"sProcessing": "加载中...",
"sLengthMenu": "显示条数: _MENU_ ",
"sZeroRecords": "没有匹配结果",
"sInfo": "第 _START_ - _END_ 项结果,共 _TOTAL_ 项",
"sInfoFiltered": "",
"sInfoPostFix": "",
"sSearch": "搜索:",
"sUrl": "",
"sEmptyTable": "表中数据为空",
"sLoadingRecords": "载入中...",
"sInfoThousands": ",",
"oPaginate": {
"sPrevious": "<", //上一页
"sNext": ">", //下一页
},
},
'aLengthMenu': [3, 10, 20, 30], //设置每页显示记录的下拉菜单
})
});
</script>
</body>
</html>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通