前端bootstrap-table列表数据使用回调函数控制显示某一列数据
1.效果
1.有可以操作用户的权限,显示操作列
2. 无操作用户的权限,不显示操作列
2.主要代码
1.前端js
<script>
var $articlesTable = $('#table').bootstrapTable('destroy').bootstrapTable({
url: '/teams/my_team_members/',
method: 'GET',
....
// 后端返回数据格式处理
responseHandler: function(res) {
if (!res.is_set_role_permission) {
$('#table').bootstrapTable('hideColumn', 'operation');
}
return {
"total": res.total, //总页数
"rows": res.rows, //数据
};
},
...
})
</script>
2.django后端接口
后端数据:
{'total': 3, 'rows': [{'user_pro': {'id': 31, 'create_time': '2023-04-19T14:38:45.337242', 'update_time': '2023-04-25T15:04:32.234793', 'created_date': '2023-04-19', 'company': 'LDC', 'department': 'SEE', 'user': 31, 'team': 3, 'role': 2}, 'user_detail': {'id': 31, 'last_login': '2023-02-21T01:13:10.215770', 'is_superuser': False, 'username': 't003gxg', 'first_name': 'Xingang', 'last_name': 'Gou', 'email': '[email protected]', 'is_staff': False, 'is_active': True, 'date_joined': '2020-09-09T01:38:00', 'groups': [2], 'user_permissions': []}, 'role': {'role_id': 2, 'role_name': '市场评估人员'}, 'update_time': '2023-04-25 15:04:32', 'permission': OrderedDict([('market_eval', '市场部评估权限')]), 'no': 3}, {'user_pro': {'id': 970, 'create_time': '2023-04-14T14:38:45.337242', 'update_time': '2023-04-24T19:42:55.943460', 'created_date': '2023-04-19', 'company': 'LDC', 'department': 'ENG', 'user': 976, 'team': 3, 'role': 1}, 'user_detail': {'id': 976, 'last_login': '2023-04-23T16:25:19.968461', 'is_superuser': True, 'username': 'CHENJ15', 'first_name': 'Jonhson', 'last_name': 'Chen', 'email': '[email protected]', 'is_staff': True, 'is_active': True, 'date_joined': '2022-07-18T08:26:00', 'groups': [1, 2], 'user_permissions': []}, 'role': {'role_id': 1, 'role_name': '技术评估人员'}, 'update_time': '2023-04-24 19:42:55', 'permission': OrderedDict([('is_superuser', '超级管理员'), ('is_team_leader', '团队负责人'), ('tech_eval', '技术部评估权限')]), 'no': 2}, {'user_pro': {'id': 1179, 'create_time': '2023-04-20T11:43:11.053016', 'update_time': '2023-04-24T18:54:41.361342', 'created_date': '2023-04-20', 'company': 'LDC', 'department': 'ENG', 'user': 1189, 'team': 3, 'role': 3}, 'user_detail': {'id': 1189, 'last_login': '2023-04-20T11:48:00', 'is_superuser': False, 'username': 'inno-leader', 'first_name': 'inno-leader', 'last_name': 'inno', 'email': '[email protected]', 'is_staff': False, 'is_active': True, 'date_joined': '2023-04-20T11:43:00', 'groups': [], 'user_permissions': []}, 'role': {'role_id': 3, 'role_name': '需求提交人员'}, 'update_time': '2023-04-24 18:54:41', 'permission': OrderedDict([('submit_requirement', '提交需求权限')]), 'no': 1}], 'is_set_role_permission': True, 'all_role': [OrderedDict([('id', 1), ('create_time', '2023-04-17T14:50:03.777968'), ('update_time', '2023-04-16T13:13:35.138401'), ('created_date', '2023-04-17'), ('name', '技术评估人员'), ('description', '技术评估人员')]), OrderedDict([('id', 2), ('create_time', '2023-04-17T14:50:14.444134'), ('update_time', '2023-04-17T13:13:16.745192'), ('created_date', '2023-04-17'), ('name', '市场评估人员'), ('description', '市场评估')]), OrderedDict([('id', 3), ('create_time', '2023-04-18T13:13:59.029016'), ('update_time', '2023-04-20T11:33:06.026676'), ('created_date', '2023-04-18'), ('name', '需求提交人员'), ('description', '需求提交')]), OrderedDict([('id', 4), ('create_time', '2023-04-20T11:17:42.140618'), ('update_time', '2023-04-21T15:02:11.440286'), ('created_date', '2023-04-20'), ('name', '团队经理'), ('description', '')]), OrderedDict([('id', 5), ('create_time', '2023-04-20T11:20:11.340991'), ('update_time', '2023-04-21T15:04:27.989899'), ('created_date', '2023-04-20'), ('name', '团队管理人员'), ('description', '')])]}
后端接口根据自己根据需要的数据按照相应的数据格式返回就可以了。
后端接口代码就不粘贴了,在django+boostrap相关分页的文章有介绍:django+bootstrap分页
三. 附上前端完整代码
{% extends "base.html" %} {% load static %}
{% block main %}
<style>
.table th, .table td, .table b {
text-align: center;
vertical-align: middle !important;
word-break: break-all;
}
</style>
{% for i in permission %}
{% if i.0 == 'is_superuser' %}
hehehehe
{% endif %}
{% endfor %}
<!-- data structure index start -->
<section class="section">
<div class="container">
<div class="row justify-content-center">
<div class="col-12 text-center">
<div class="section-title mb-4 pb-2">
{% if team_name or company %}
<h4 class="title mb-4">{{ company }} - {{ team_name }}</h4>
{% else %}
<h5 class="title mb-4">未设置所属公司或未加入团队,请联系管理员进行设置</h5>
{% endif %}
</div>
</div><!--end col-->
</div><!--end row-->
<div id="toolbar">
<div class="form-inline" role="form">
{% if 'is_team_leader' in permission.keys or 'is_superuser' in permission.keys or 'is_set_permission' in permission.keys %}
<button id="addTeamMember" class="btn btn-soft-primary btn-sm" data-toggle="modal"
data-target="#addUserModal">
<i class="fa fa-plus"></i> 添加团队成员
</button>
{% endif %}
{% if 'is_superuser' in permission.keys %}
<button style="margin-left: 5px" class="btn btn-soft-primary btn-sm" onclick="window.open('/admin/teams/team/add/')">
<i class="fa fa-plus"></i> 创建团队
</button>
<button style="margin-left: 5px" class="btn btn-soft-primary btn-sm" onclick="window.open('/admin/registration/')">
<i class="fas fa-edit"></i> 角色权限管理
</button>
{% endif %}
<!-- 自定义搜索查询 -->
<div class="input-group" style="left: 5px;display: none"><input id="search-keyword"
class="form-control search-input" type="search"
placeholder="Search" autocomplete="off">
<div class="input-group-append">
<button id="search-button" class="btn btn-soft-primary btn-sm" type="button" name="search"
title="Search">
<i class="fa fa-search"></i></button>
</div>
</div>
</div>
</div>
<!-- data structure index pagination -->
<table id="table"
class="table-sm small"
data-pagination="true"
data-buttons-class="soft-primary btn-sm"
data-sort-name="created_date"
data-sort-order="desc"
data-remember-order="true"
data-show-fullscreen="true"
data-show-columns="true"
data-show-columns-toggle-all="true"
data-show-export="true"
data-click-to-select="true"
data-toolbar="#toolbar"
style="table-layout: fixed;height: auto"
>
<thead class="thead-light">
</table>
</div>
</section>
<!-- data structure index end -->
<!-- 添加团队成员弹窗 -->
<div class="modal fade" id="addUserModal" style="top: 100px;" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="myModalLabel">
添加团队成员
</h5>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
</div>
<div class="modal-body">
<form method="post" action="" class="form-horizontal" role="form" id="userEmailForm" style="margin: 5px;">
<div class="form-group">
<input type="text" class="form-control" name="email" value="" id="email"
placeholder="请输入团队成员邮箱">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary" onclick="add_team_member()">提交</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
<!-- 修改角色弹窗 -->
<div class="modal fade" id="changeUserRoleModal" style="top: 100px;" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="changeRoleModalLabel">
修改团队成员角色
</h5>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
</div>
<div class="modal-body">
<form method="post" action="" class="form-horizontal" id="changeUserRoleForm" style="">
<div class="col-sm-6">
<input type="hidden" class="form-control" id="change_user_id" value="">
</div>
<div class="form-group">
<label for="" class="col-sm-6 control-label">角色:</label>
<div class="col-sm-9">
<select onchange="get_role_permission()" name="role_id" class="custom-select" id="userRoleNameId">
<option selected="selected" value="0">请选择</option>
</select>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-8">该角色拥有的权限:</label>
<div class="col-sm-12">
<div id="rolePermissionId" class="form-text text-muted"></div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary" onclick="change_user_role()">提交</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
{% endblock %}
{% block script %}
<!-- JS for download table-->
<script>
var $table = $('#table')
$(function () {
$('#toolbar').find('select').change(function () {
$table.bootstrapTable('destroy').bootstrapTable({
exportDataType: $(this).val(),
exportTypes: ['excel', 'xml', 'csv', 'txt', 'sql'],
columns: [
{
field: 'state',
checkbox: true,
visible: $(this).val() === 'selected'
}
]
})
}).trigger('change')
})
</script>
<!-- JS for pagination -->
<script>
var $articlesTable = $('#table').bootstrapTable('destroy').bootstrapTable({
url: '/teams/my_team_members/',
method: 'GET',
dataType: "json",
uniqueId: 'id', //每一行的唯一标识,一般为主键列
striped: false, //是否显示行间隔色
cache: false,
sortName: 'update_time',
sortable: true,
sortOrder: 'desc',
sidePagination: "server",
undefinedText: '--',
singleSelect: true,
toolbar: '#toolbar', //工具按钮用哪个容器
showToggle: true, //是否显示详细视图和列表视图的切换按钮
strictSearch: true,
clickToSelect: true,
pagination: true, //是否显示分页(*)
showRefresh: true, //是否显示刷新按钮
pageNumber: 1, //初始化加载第一页,默认第一页
pageSize: 5, //每页的记录行数(*)
pageList: [5, 20, 50, 100, 'all'],
paginationPreText: "<",
paginationNextText: ">",
queryParamsType: "",
maxHeight: "200px",
queryParams: function (params) {
var query_params = {
'pageSize': params.pageSize,
'pageNumber': params.pageNumber,
'search_kw': $('#search-keyword').val(), // 查询框中的参数传递给后台
'sortName': params.sortName,
'sortOrder': params.sortOrder
};
return query_params;
},
//返回数据格式处理
responseHandler: function(res) {
if (res.all_role) {
for (var i=0; i < res.all_role.length; i++) {
$("#userRoleNameId").append('<option value='+res.all_role[i].id+'>'+res.all_role[i].name+'</option>');
}
}
if (!res.is_set_role_permission) {
$('#table').bootstrapTable('hideColumn', 'operation');
}
return {
"total": res.total, //总页数
"rows": res.rows, //数据
};
},
columns: [
{
field: 'no',
title: 'No',
align: 'center',
halign: 'center',
width: '50px',
visible: true,
formatter: function (value, row, index) {
var result = "";
result += '<a href="/teams/data_structure_detail/' + row.id + '/" target="_blank">' + row.no + '</a>'
return result
}
},
{
field: 'username',
title: '姓名',
align: 'left',
halign: 'center',
width: '120px',
visible: true,
formatter: function (value, row, index) {
return row.user_detail.first_name + row.user_detail.last_name
}
},
{
field: 'email',
title: '邮箱',
align: 'left',
halign: 'center',
width: '180px',
visible: true,
formatter: function (value, row, index) {
return row.user_detail.email
}
},
{
field: 'company',
title: '公司',
align: 'center',
halign: 'center',
width: '100px',
visible: true,
formatter: function (value, row, index) {
return row.user_pro.company
}
},
{
field: 'role',
title: '角色',
align: 'center',
halign: 'center',
width: '120px',
visible: true,
formatter: function (value, row, index) {
return row.role.role_name
}
},
{
field: 'permission',
title: '角色权限',
align: 'left',
halign: 'center',
width: '170px',
visible: true,
formatter: function (value, row, index) {
var result = "";
for (var key in row.permission) {
result += '<span>'+row.permission[key]+'; </span>'
}
return result
}
},
{
field: 'update_time',
title: '更新时间',
align: 'center',
halign: 'center',
width: '160px',
visible: true,
sortable: true,
},
{
field: 'operation',
title: '操作',
halign: 'center',
width: '120px',
visible: true,
formatter: function (value, row, index) {
{#console.log(row)#}
var result = "";
result += '<a href="#" οnclick="get_user_role_info('+JSON.stringify(row).replace(/\"/g,"'")+')" data-toggle="modal" data-target="#changeUserRoleModal">修改角色</a> '
result += '<a href="#" οnclick="del_team_member('+JSON.stringify(row.user_detail).replace(/\"/g,"'")+')"><i class="fas fa-trash-alt"></i></a>'
return result
}
},
],
onl oadError: function (data) {
console.log("数据加载失败!", "错误提示");
$.messager.alert({title: '提示', msg: '数据加载失败!', icon: 'warning', top: 200});
},
});
// 搜索查询按钮触发事件
$("#search-button").click(function () {
console.log($('#search-keyword').val())
$('#table').bootstrapTable(('refresh'));
})
// 回车执行搜索
$("#search-keyword").bind('keyup', function (event) {
console.log($('#search-keyword').val())
$('#table').bootstrapTable(('refresh'));
})
</script>
<!-- JS for edit data -->
<script>
function get_role_permission() {
var role_id = $('#userRoleNameId').val();
console.log(role_id)
if (role_id === '0') {
console.log(role_id)
$('#rolePermissionId').text('')
return;
}
$.ajax({
url: server_url + '/users/get_role_permission/'+role_id+'/',
method: 'GET',
processData: false,
contentType: false,
cache: false,
success: function (data) {
if (data.status === 200) {
console.log("data:" + data.msg);
var userRolePermission = ""
for (var key in data.msg) {
userRolePermission += data.msg[key]+'; '
}
$('#rolePermissionId').text(userRolePermission)
return;
}
console.log(data)
$.messager.alert({title: '提示', msg: data.msg , icon: 'warning'});
},
//请求失败,包含具体的错误信息
error: function (data) {
console.log(data.msg);
}
});
}
function get_user_role_info(obj) {
console.log(obj)
var t = document.getElementById("userRoleNameId");
if (obj.role.role_id) {
t[obj.role.role_id].selected = true
} else {
t[0].selected = true
}
var userRolePermission = ""
for (var key in obj.permission) {
userRolePermission += obj.permission[key]+'; '
}
$('#change_user_id').val(obj.user_detail.id)
$('#rolePermissionId').text(userRolePermission)
}
function change_user_role() {
var formData = new FormData($("#changeUserRoleForm")[0]);
var change_user_id = $('#change_user_id').val();
console.log(change_user_id)
$.ajax({
url: server_url + '/users/change_user_role/'+change_user_id+'/',
method: 'POST',
data: formData,
dataType: "json",
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log("data:" + data);
if (data.status === 200) {
console.log("data:" + data.msg);
$.messager.show({
title: '提示',
msg: data.msg,
showType: '',
timeout: 500,
width: 300,
height:130,
style: {top: 200}
});
$('#changeUserRoleModal').modal('hide');
document.getElementById("userRoleNameId").options.length=1;
$('#table').bootstrapTable('refresh');
return;
}
console.log(data)
$.messager.alert({title: '提示', msg: data.msg , icon: 'warning'});
},
//请求失败,包含具体的错误信息
error: function (data) {
console.log(data.msg);
}
});
}
function del_team_member(obj) {
console.log(obj)
$.messager.confirm({
title: '提示', msg: '是否将['+obj.first_name+obj.last_name+']用户从团队中移除?', top: 200,
fn: function (r) {
if (r) {
$.ajax({
url: server_url + '/teams/remove_team_member/' + obj.id + '/',
method: 'get',
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log("data:" + data);
console.log("data:" + data.status);
if (data.status === 200) {
{#$.messager.alert({title: '提示', msg: data.msg, icon: 'warning', top: 200,});#}
$.messager.show({
title: '提示',
msg: data.msg,
showType: '',
timeout: 500,
style: {top: 200}
});
console.log("data:" + data.msg);
document.getElementById("userRoleNameId").options.length=1;
$('#table').bootstrapTable('refresh');
return
}
console.log(data)
$.messager.alert({title: '提示', msg: '权限不足或服务请求异常,数据无法删除!', icon: 'warning', top: 200});
},
//请求失败,包含具体的错误信息
error: function (data) {
console.log('error' + data.msg);
$.messager.alert({title: '提示', msg: '请求服务错误或当前网络不佳!', icon: 'warning', top: 200});
}
});
}
}
});
}
</script>
<!-- JS for add team member -->
<script>
function add_team_member() {
var formData = new FormData($("#userEmailForm")[0]);
var email = $('#email').val()
if (email === '') {
$.messager.alert("提示", '请输入团队成员邮箱!', "info");
return
}
$.ajax({
url: server_url + '/teams/add_team_member/',
method: 'POST',
data: formData,
dataType: "json",
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log("data:" + data);
console.log("data:" + data.res);
if (data.status === 200) {
console.log("data:" + data.msg);
{#$.messager.alert("提示", data.msg, "info");#}
$.messager.show({
title: '提示',
msg: data.msg,
showType: '',
timeout: 500,
width: 300,
height:130,
style: {top: 200}
});
$('#addUserModal').modal('hide');
$('#email').val('');
document.getElementById("userRoleNameId").options.length=1;
$('#table').bootstrapTable('refresh');
{#window.setTimeout("window.location=server_url+'/teams/my_team/'", 300);#}
return;
}
console.log(data)
$.messager.alert({title: '提示', msg: data.msg , icon: 'warning'});
},
//请求失败,包含具体的错误信息
error: function (data) {
console.log(data.msg);
}
});
}
</script>
{% endblock %}
以上就是关于前端bootstrap-table列表页面控制显示某列的介绍,希望对你有所帮助。