BootstrapTable简单的使用
Bootstrap table是一款基于 Bootstrap 的 jQuery 表格插件,通过简单的设置,就可以拥有强大的单选、多选、排序、分页,以及编辑、导出、过滤(扩展)等等的功能。
本篇文章介绍bootstrap-table的简单的使用(查询,新增,修改,删除),在看之前,需要有一点点bootstrap的基础知识,很多bootstrap的相关知识点就不介绍了,只讲bootstrap-table的相关内容。
引入相关文件
bootstrap-table 的使用非常简单,只需要像引用JQuery一样将js文件以及css文件引入到html文档中即可,为了更快的访问js文件,可以访问cdn,这里将cdn链接放上,如果没有链接至互联网,请将文件下载到本地,在引入至项目中,下面是引用的文件,文件存放在了cdn节点
<script src="https://cdn.staticfile.org/jquery/2.1.0/jquery.min.js"></script>/<!--JQuery-->
<script src="http://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script><!--bootstrap-->
<script src="http://cdn.staticfile.org/bootstrap-table/1.9.0/bootstrap-table.min.js"></script><!--bootstrap-table-->
<script src="http://cdn.staticfile.org/bootstrap-table/1.9.0/locale/bootstrap-table-zh-CN.min.js"></script><!--汉化文件-->
可以看到引入的文件有JQuery,由于bootstrap是基于JQuery 的一个框架,引入Bootstrap文件之前需要引入JQuery,而bootstrap-table是基于bootstrap的,所以必须引入JQuery;下面是Bootstrap框架的js,继续往下是bootstrap-table的js文件,最下面是汉化的js文件。引入js文件之后,为了美观还需要引入css(外部样式表)文件,也是bootstrap框架的文件,如果不引入,没有样式,界面很不美观;下面是需要引入的bootstrap的css文件和bootstrap-table需要用到的css文件。
<link rel="stylesheet" href="http://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="http://cdn.staticfile.org/bootstrap-table/1.9.0/bootstrap-table.min.css">
简单的使用
首先,我把这个案例的全部html代码和css代码放上去,然后一点一点拆解
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>学生信息</title>
<link rel="stylesheet" href="http://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="http://cdn.staticfile.org/bootstrap-table/1.9.0/bootstrap-table.min.css">
<!-- <link rel="stylesheet" href="/css/style.min862f.css">-->
<script src="https://cdn.staticfile.org/jquery/2.1.0/jquery.min.js"></script><!---->
<script src="http://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://cdn.staticfile.org/bootstrap-table/1.9.0/bootstrap-table.min.js"></script>
<script src="http://cdn.staticfile.org/bootstrap-table/1.9.0/locale/bootstrap-table-zh-CN.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<form class="navbar-form navbar-left" id="searchForm">
<div class="form-group">
<input type="text" class="form-control" id="searStr" name="searStr" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">搜索</button>
<button type="button" class="btn btn-default" onclick="(function(){$('#stuDetailModal').modal('show')})()">新增</button>
</form>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div class="container">
<div class="row">
<table id="table"></table>
</div>
</div>
<div class="modal fade" tabindex="-1" role="dialog" id="stuDetailModal">
<div class="modal-dialog" role="document" style="width: 70%">
<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>
<h4 class="modal-title">学生信息</h4>
</div>
<div class="modal-body">
<input type="hidden" name="stuIndex" id="stuIndex">
<div class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">学号</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="stuId" name="stuId" value="" disabled="disabled" readonly="readonly"/>
</div>
<label class="col-sm-2 control-label">姓名</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="stuName" name="stuName" value="" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">性别</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="stuGender" name="stuGender" value="" />
</div>
<label class="col-sm-2 control-label">年龄</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="stuAge" name="stuAge" value="" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">电话</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="stuPhone" name="stuPhone" value="" />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-primary" onclick="saveStudentInfo()">保存</button>
<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">关闭</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script type="text/javascript">
function queryParams(params) {
return {type: "owner", direction: "desc", limit: params.limit, offset: params.offset}
}
$(function(){
searchMusicList();
})
function showStudentInfoDetailModal(rid) {
$('#stuDetailModal').modal('show');
$.get("/students3/getStudentByStuId",{stuId:rid}, function (res) {
res = JSON.parse(res);
if (res.result == 'success'){
if (res != null) {
$("#stuId").val(res.StudentInfo.stu_id);
$("#stuName").val(res.StudentInfo.stu_name);
$("#stuGender").val(res.StudentInfo.stu_gender);
$("#stuPhone").val(res.StudentInfo.stu_phone);
$("#stuAge").val(res.StudentInfo.stu_age);
}else {
alert('没有找到学生信息');
}
}else if (res.result == 'fail'){
alert('获取学生信息失败!');
}else{
alert(res.result);
}
})
}
function searchMusicList() {
$('#table').bootstrapTable('destroy');
$('#table').bootstrapTable({
url: "/students3/getAllStudent",
height:500,
dataType: "json",
pagination: true,
pageSize: 30,
queryParams:queryParams,
sortable:true,
sidePagination: "server",
pageList: [30, 50],
columns: [{
title: '序号',
width: "5%",
field: 'rowNo',
}, {
field: 'stu_id',
title: '学号',
width: "10%",
sortable:true
}, {
field: 'stu_name',
title: '姓名',
width: "10%",
sortable:true
}, {
field: 'stu_age',
title: '年龄',
width: "10%",
sortable:true
}, {
field: 'stu_gender',
sortable:true,
title: '性别',
width: "10%", formatter: function (value, row, index) {
if (value == 'M') return '男';
else if (value == 'F') return '女';
else return value;
}
}, {
field: 'stu_phone',
title: '联系方式',
width: "10%",
}, {
title: '操作',
class: 'text-center',
width: '20%',
formatter: function (value, row, index) {
let res = "<button class='btn btn-sm btn-info' οnclick='showStudentInfoDetailModal(" + row.stu_id + ")' >详情</button> ";
res += "<button class='btn btn-sm btn-primary' οnclick='modifyStudentInfoDetailModal(" +index + ")'>修改</button> ";
res += "<button class='btn btn-sm btn-danger' οnclick='removeStudentBuId(" +index + ")'>删除</button>";
return res;
}
},],onPostBody: function (value) {
// 解决模态框加载table数据的时候,底部数据超出表格的问题
$(".fixed-table-container").css('padding-bottom', '37px');
}
});
return false;
}
$("#searchForm").submit(function (e) {
let option = $('#table').bootstrapTable('getOptions');
option.queryParams = function(params){
let searStr = document.getElementById('searStr').value;
params.stuname = searStr;
return params;
}
$('#table').bootstrapTable('refresh',option);
return false;
})
function modifyStudentInfoDetailModal(i){
const stuInfo = $('#table').bootstrapTable('getData')[i];
$("#stuId").val(stuInfo.stu_id);
$("#stuName").val(stuInfo.stu_name);
$("#stuGender").val(stuInfo.stu_gender);
$("#stuPhone").val(stuInfo.stu_phone);
$("#stuAge").val(stuInfo.stu_age);
$("#stuIndex").val(i);
$('#stuDetailModal').modal('show');
}
function saveStudentInfo(){
const stuId = $("#stuId").val();
const stuName = $("#stuName").val();
const stuGender = $("#stuGender").val();
const stuPhone = $("#stuPhone").val();
const stuAge = $("#stuAge").val();
const stuIndex = $("#stuIndex").val();
const student = {stu_id: stuId, stu_name: stuName, stu_gender: stuGender, stu_phone: stuPhone, stu_age: stuAge};
$.post("/students3/saveStudentInfo" ,student, function (res) {
res = JSON.parse(res);
if (res.result == 'success' ){
if (res.flag == true){
$('#stuDetailModal').modal('hide');
alert("更新成功!");
if(stuId == '' || stuId == null){
student.stu_id = res.stuId;
$('#table').bootstrapTable('prepend', student);
} else {
$("#table").bootstrapTable("updateRow", {
index:stuIndex,//更新行索引,0起始
replace:false,//合并or替换行数据,true替换,false合并,默认false
row:student
});
}
}else{
alert('学生信息更新失败,请检查!');
$('#stuDetailModal').modal('hide');
}
}else if (res.result == 'fail' ){
alert('学生信息更新失败');
}else{
alert(res.result);
}
})
}
function removeStudentBuId(i){
const stuInfo = $('#table').bootstrapTable('getData')[i];
let flag = confirm(`确定要删除姓名为: ${stuInfo.stu_name} 学号为: ${stuInfo.stu_id} 的学生吗?`);
if (!flag) return false;
$.post("/students3/removeStudentBuId" , stuInfo, function (res) {
res = JSON.parse(res);
if (res.result == 'success' ){
if (res.flag == true){
$("#table").bootstrapTable('remove', {field:'stu_id',values:[stuInfo.stu_id]});
alert("删除成功!");
}else{
alert('学生信息删除失败,请检查!');
$('#stuDetailModal').modal('hide');
}
}else if (res.result == 'fail' ){
alert('学生信息删除失败');
}else{
alert(res.result);
}
})
}
$('#stuDetailModal').on('hidden.bs.modal', function () {//学生信息模态框关闭,清空缓存
$("#stuId").val('');
$("#stuName").val('');
$("#stuGender").val('');
$("#stuPhone").val('');
$("#stuAge").val('');
$("#stuIndex").val('');
})
</script>
</body>
</html>
bootstrap-table的初始化
首先,bootstrap-table渲染数据使用的是table标签,需要创建一个table标签用来渲染等会即将出现的内容,只需要一个table标签然后配置一下相关参数bootstrap-table会帮我们渲染出相对应的界面,生成相关标签。下面是用来等会渲染数据的table,id为table,外层div的container类是bootstrap的样式,为了拉开两边的距离。row的类是定义了这是一行,这样,row会被撑开,不至于布局错乱。
<div class="container">
<div class="row">
<table id="table"></table>
</div>
</div>
接下来看bootstrap-table的js代码
function queryParams(params) {
return {type: "owner", direction: "desc", limit: params.limit, offset: params.offset}
}
function searchMusicList() {
$('#table').bootstrapTable('destroy');
$('#table').bootstrapTable({
url: "/students3/getAllStudent",
height:500,
dataType: "json",
pagination: true,
pageSize: 30,
queryParams:queryParams,
sortable:true,
sidePagination: "server",
pageList: [30, 50],
columns: [{
title: '序号',
width: "5%",
field: 'rowNo',
}, {
field: 'stu_id',
title: '学号',
width: "10%",
sortable:true
}, {
field: 'stu_name',
title: '姓名',
width: "10%",
sortable:true
}, {
field: 'stu_age',
title: '年龄',
width: "10%",
sortable:true
}, {
field: 'stu_gender',
sortable:true,
title: '性别',
width: "10%", formatter: function (value, row, index) {
if (value == 'M') return '男';
else if (value == 'F') return '女';
else return value;
}
}, {
field: 'stu_phone',
title: '联系方式',
width: "10%",
}, {
title: '操作',
class: 'text-center',
width: '20%',
formatter: function (value, row, index) {
let res = "<button class='btn btn-sm btn-info' οnclick='showStudentInfoDetailModal(" + row.stu_id + ")' >详情</button> ";
res += "<button class='btn btn-sm btn-primary' οnclick='modifyStudentInfoDetailModal(" +index + ")'>修改</button> ";
res += "<button class='btn btn-sm btn-danger' οnclick='removeStudentBuId(" +index + ")'>删除</button>";
return res;
}
},],onPostBody: function (value) {
// 解决模态框加载table数据的时候,底部数据超出表格的问题
$(".fixed-table-container").css('padding-bottom', '37px');
}
});
return false;
}
渲染数据很简单,只需要配置这些就能够将数据渲染出来,更多的配置讲解这里也就不过多介绍了,文档写得比我要更清楚,这里主要讲简单的应用,一些简单的增删改查。bootstrap-table需要的数据格式如下
{
"result": "success",
"lastNum": 0,
"total": 1031,
"recordsFiltered": 1031,
"rows": [{
"rowNo": 1,
"stu_id": 2,
"stu_name": "张三",
"stu_gender": "男",
"stu_age": 11,
"stu_phone": "15036810833"
}, {
"rowNo": 2,
"stu_id": 3,
"stu_name": "张五",
"stu_gender": "男",
"stu_age": 18,
"stu_phone": "15036810833"
}],
"recordsTotal": 1031
}
这里过多的重复的数据删除了,不做过多展示,这里面的参数“total”是一共有多少条数据,“rows”是具体的数据,如果响应的数据不是这种,可以用bootstrap-table里面的“responseHandler”方法进行格式化,比如响应的数据是这样的
{
"result": "success",
"allCount": 1031,
"data": [{
"rowNo": 1,
"stu_id": 2,
"stu_name": "张三",
"stu_gender": "男",
"stu_age": 11,
"stu_phone": "15036810833"
}, {
"rowNo": 2,
"stu_id": 3,
"stu_name": "张五",
"stu_gender": "男",
"stu_age": 18,
"stu_phone": "15036810833"
}],
}
这样的数据bootstrap-table是不能识别的,需要格式化成bootstrap-table能识别的数据格式,这时候就可以用“responseHandler”进行格式化,写法如下
$('#table').bootstrapTable('destroy');
$('#table').bootstrapTable({
url: "/students3/getAllStudent",
height:500,
dataType: "json",
pagination: true,
pageSize: 30,
queryParams:queryParams,
sortable:true,
responseHandler:function(res){
return {
"total":res.allCount,
"rows":res.data
}
},
sidePagination: "server",
pageList: [30, 50],
columns: [{
title: '序号',
width: "5%",
field: 'rowNo',
}, {
field: 'stu_id',
title: '学号',
width: "10%",
sortable:true
}, {
field: 'stu_name',
title: '姓名',
width: "10%",
sortable:true
}, {
field: 'stu_age',
title: '年龄',
width: "10%",
sortable:true
}, {
field: 'stu_gender',
sortable:true,
title: '性别',
width: "10%", formatter: function (value, row, index) {
if (value == 'M') return '男';
else if (value == 'F') return '女';
else return value;
}
}, {
field: 'stu_phone',
title: '联系方式',
width: "10%",
}, {
field: 'stu_id',
title: '操作',
class: 'text-center',
width: '20%',
formatter: function (value, row, index) {
let res = "<button class='btn btn-sm btn-info' οnclick='showStudentInfoDetailModal(" + row.stu_id + ")' >详情</button> ";
res += "<button class='btn btn-sm btn-primary' οnclick='modifyStudentInfoDetailModal(" +index + ")'>修改</button> ";
res += "<button class='btn btn-sm btn-danger' οnclick='removeStudentBuId(" +index + ")'>删除</button>";
return res;
}
}]
});
return false;
}
这样经过格式化,可以不用改变后台的响应数据格式也能渲染出来,说完数据怎么渲染下面说一下数据的查询,其实bootstrap-table帮我们存了一份虚拟的数据在里面,当我们需要的时候就可以拿出来,哪怕渲染的时候没有将他显示出来,也是可以拿到的,下面介绍一下怎么取出来。观察上面的代码可以看到在操作列是有表达式的,以及性别列也是有表达式的,就是bootstrap-table的columns属性,这是一个数组,数组里面是一个一个的对象,
{
field: 'stu_id',
title: '操作',
class: 'text-center',
width: '20%',
formatter: function (value, row, index) {
let res = "<button class='btn btn-sm btn-info' οnclick='showStudentInfoDetailModal(" + row.stu_id + ")' >详情</button> ";
res += "<button class='btn btn-sm btn-primary' οnclick='modifyStudentInfoDetailModal(" +index + ")'>修改</button> ";
res += "<button class='btn btn-sm btn-danger' οnclick='removeStudentBuId(" +index + ")'>删除</button>";
return res;
}
}
对象里面的“formatter”属性可以是一个方法,这个方法有三个形参,分别是“value”, “row”, “index”,第一个就是当前列"field"属性里面的值,第二个“row”是当前行的对象也就是前面讲到的后台渲染数据的时候“rows”里面的每一个数据
{
"rowNo": 2,
"stu_id": 3,
"stu_name": "张五",
"stu_gender": "男",
"stu_age": 18,
"stu_phone": "15036810833"
}
通过row.就能进行访问,“index”是当前行的索引,比如第一行数据是 0 第二行数据是 1,可以看到我写的函数里面写了一些html代码,通过拼接的方式将数据渲染到html上,我写的html代码是三个按钮,一个查看,一个修改,一个删除,这里详情就不讲了,就是简单的查看。
查询,修改
下面直接讲修改,修改的方法如下(其实上面也有了,不过为了不上下翻代码就写在这吧)
/**
* 将学生信息渲染到对应表单里面
* @param Number i 操作的索引
*/
function modifyStudentInfoDetailModal(i){
const stuInfo = $('#table').bootstrapTable('getData')[i];
$("#stuId").val(stuInfo.stu_id);
$("#stuName").val(stuInfo.stu_name);
$("#stuGender").val(stuInfo.stu_gender);
$("#stuPhone").val(stuInfo.stu_phone);
$("#stuAge").val(stuInfo.stu_age);
$("#stuIndex").val(i);//记录操作索引
$('#stuDetailModal').modal('show');//打开模态框
}
function saveStudentInfo(){
const stuId = $("#stuId").val();
const stuName = $("#stuName").val();
const stuGender = $("#stuGender").val();
const stuPhone = $("#stuPhone").val();
const stuAge = $("#stuAge").val();
const stuIndex = $("#stuIndex").val();
const student = {stu_id: stuId, stu_name: stuName, stu_gender: stuGender, stu_phone: stuPhone, stu_age: stuAge};
$.post("/students3/saveStudentInfo" ,student, function (res) {
res = JSON.parse(res);
if (res.result == 'success' ){
if (res.flag == true){
$('#stuDetailModal').modal('hide');
alert("更新成功!");
if(stuId == '' || stuId == null){
student.stu_id = res.stuId;
$('#table').bootstrapTable('prepend', student);
} else {
$("#table").bootstrapTable("updateRow", {
index:stuIndex,//更新行索引,0起始
replace:false,//合并or替换行数据,true替换,false合并,默认false
row:student
});
}
}else{
alert('学生信息更新失败,请检查!');
$('#stuDetailModal').modal('hide');
}
}else if (res.result == 'fail' ){
alert('学生信息更新失败');
}else{
alert(res.result);
}
})
}
modifyStudentInfoDetailModal 这个方法是将数据渲染到页面上,形参i就是当前要操作数据的索引,这个是bootstrap-table需要用到的,取到对应的数据之后,渲染到html上,然后记录下当前操作的索引,获取数据方式很简单,使用 “bootstrapTable(‘getData’)”就能拿到,这个方法返回值是数组,然后根据索引取对应的数据就行了。接下来讲保存,保存其实就是搜集表单信息,然后讲数据发送到后台,然后等待响应结果,响应成功之后刷新表格或者将数据更新到bootstrap-table,这里我选择的是后者,相信大多数人和我一样,在编程的时候尽量减少服务器和客户端传输的数据量,比如这个更新学生信息的例子,如果直接调用$(‘#table’).bootstrapTable(‘refresh’)会更简单,但是这样会导致大量无用数据在网络中传输,因为我们要的就是一个修改的结果,数据也是前台传过去的,服务器也会响应一个结果,成功或者失败,所以直接拿当前结果更新到bootstrap-table中更好,而不是增加数据库的查询,增加前后台无用的交互。回到正题,这里保存很简单,搜集表格信息,找到操作的索引,然后调用bootstrap的"updateRow"方法将数据渲染到表格中。
删除
接下来讲一下删除,删除更简单了,方法如下
function removeStudentBuId(i){
const stuInfo = $('#table').bootstrapTable('getData')[i];
let flag = confirm(`确定要删除姓名为: ${stuInfo.stu_name} 学号为: ${stuInfo.stu_id} 的学生吗?`);
if (!flag) return false;
$.post("/students3/removeStudentBuId" , stuInfo, function (res) {
res = JSON.parse(res);
if (res.result == 'success' ){
if (res.flag == true){
$("#table").bootstrapTable('remove', {field:'stu_id',values:[stuInfo.stu_id]});
alert("删除成功!");
}else{
alert('学生信息删除失败,请检查!');
$('#stuDetailModal').modal('hide');
}
}else if (res.result == 'fail' ){
alert('学生信息删除失败');
}else{
alert(res.result);
}
})
}
根据索引拿到要删除的数据,提示一下,这里我将整个student都传输到后台了,其实只要能识别是这个学生就行,不要把整个对象都传过去,然后更新bootstrap-table的时候调用bootstrap-table的remove方法就行了,需要的参数也是和服务器删除相似(其实服务器是假删除),只需要能标识出这个学生就行。
新增
点击搜索旁边的新增按钮,输入学生信息,和修改是一样的,这个判定是由后台进行判定,如果传过去的数据有学生id就是修改,否则为新增,模态框每次关闭都会清空相关信息,不用担心数据残留,这里的保存还是有bug的,比如序号没有更新,由于序号是后后台生成的,所以需要重新后台刷新数据,这里没有从后台取数据,所以序号是错的,但是可以通过前端写js进行修复,以后有时间再处理这个bug
总结
很简单的操作,主要讲bootstrap-table 的简单使用
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?