Bootstrap Bootstrap表格插件bootstrap-table配置与应用小结3

简介: Bootstrap Bootstrap表格插件bootstrap-table配置与应用小结3

 

获取选中行索引

rowIndex = $('#' + roleTableID).find('tbody>tr.selected').first().attr('data-index');

 

这里为啥要获取,为啥可以这么获取?原因是这样的,通过选择表记录行,然后点击表格上方的修改按钮修改对应记录,这种情况下,无法直接获取对应行记录的索引,导致没法更新对应记录行,所以需要获取索引,没找到对应,至于为啥这么获取,是由table 表结构决定的,如下图:

 

 

 

删除记录

/**

* 删除角色

*/

function deleteRole(flag) {

var idArray = [];

if (flag == 'byTopDeleteBtn') { // 通过点击表格上方的删除按钮进入

rowArray = $('#' + roleTableID).bootstrapTable('getSelections');

if (rowArray.length <1) {

alert('请先选择要删除的角色');

return;

       }

   } else if (flag == 'byRowDeleteBtn') { // 通过点击行右侧的删除按钮进入

idArray.push(currentRole.id);

   }

 

var mark = true; // 标记是否删除成功

if (confirm('是否删除选中记录?')) {

$.each(rowArray, function() {

idArray.push(this.id);

       });

 

$.ajax({

type: "POST",

url: deleteRoleURL,

async: false,

data: {'idArray':"" + idArray + ""},

success: function (result) {

if (result.success == 'true') {

alert(result.msg);

// 批量删除对应记录行

$('#' + roleTableID).bootstrapTable('remove',{ field: 'id', values: idArray});

//$('#' + roleTableID).bootstrapTable('refresh');

} else {

alert(result.msg + "" + result.reason);

               }

           },

error: function(XmlHttpRequest, textStatus, errorThrown) {

alert('删除角色请求失败' + XmlHttpRequest.responseText);

           }

       });

   }

}

 

删除记录

$('#tableID').bootstrapTable('remove',{ field: 'id', values: idArray});

 

field: 需要删除的行的 field 名称,

values:  需要删除的行的值,类型为数组。

 

获取选中行

$('#tableID').bootstrapTable('getSelections');

getSelections   返回所选的行,当没有选择任何行的时候返回一个空数组

 

后台代码片段

查询表数据

def role_tabe_data(request):

'''

获取角色表数据

:param request:

   '''

 

if request.method == 'GET':

       rows = [] # 用于存储记录行

table_data = {"total": 0, "rows": []}

 

try:

           params = request.GET

 

# search = params.get('search')          # 通过表格插件自带的搜索框搜索的内容 # 如果要实现,需要确认按哪些列搜索

page_size =  int(params.get('limit'))  # 每页记录数

offset = int(params.get('offset'))

           page_index =  offset // page_size + 1  # 第几页数据

 

sort = params.get('sort')       # 排序字段 // 初始化页面时,无排序获取值为None

order = params.get('order')     # 排序方式

role_name = params.get('roleNameQ')   # 角色名称

start_time = params.get('startTime') # 开始时间

end_time = params.get('endTime')     # 结束时间

 

 

sql_ddl = 'select id, name, remark, is_enable, creater, create_time, modifier,  modify_time from website_role '

 

if role_name:

               sql_ddl = sql_ddl + "where name like '%s%s' " % (role_name, '%%')

               temp_mark = 1

else:

               temp_mark = 0

 

if start_time:

if temp_mark:

                   sql_ddl = sql_ddl + "and create_time>='%s' " % start_time

else:

                   sql_ddl = sql_ddl + "where create_time>='%s' " % start_time

               temp_mark = 1

else:

               temp_mark = 0

 

if end_time:

if temp_mark:

                   sql_ddl = sql_ddl + "and create_time<='%s' " % end_time

else:

                   sql_ddl = sql_ddl + "where create_time<='%s' " % start_time

 

 

if order and sort:

               sql_ddl = sql_ddl + 'order by %s %s' % (sort, order)

else:

               sql_ddl = sql_ddl + 'order by id desc' # 最新创建的排在最前面

 

records = Role.objects.raw(sql_ddl)

           records = json.loads(serializers.serialize('json', records), encoding='utf-8')

 

           table_data["total"] = len(records)

 

           paginator = Paginator(records, page_size) # 设置每页展示的数据

try:

               page = paginator.page(page_index)

except PageNotAnInteger as e: # 如果请求的页面编号不存在,返回第一页数据

logger.warn('%s' % e)

               page = paginator.page(1)

except EmptyPage as e: # 如果请求页面,超出页面范围,返回最后一页数据

logger.warn('%s' % e)

               page = paginator.page(paginator.num_pages)

           records = page.object_list

 

for record in records:

               row = {}

               row['id'] = record['pk']

               row.update(record['fields'])

if row['is_enable']:

                   row['is_enable'] = '是'

else:

                   row['is_enable'] = '否'

rows.append(row)

 

           table_data["rows"] =  rows

           content = {'data':table_data, 'msg':'获取角色信息成功', 'success':'true', 'reason': ''}

except Exception as e:

           logger.error('getting roles info data failed: %s' % e)

           content = {'data':[], 'msg':'获取角色信息失败',  'success':'false', 'reason': '%s' % e}

else:

       logger.error('only get method allowed for getting roles data')

       content = {'data':[], 'msg':'获取角色信息失败',  'success':'false', 'reason': 'only get method allowed for getting roles data'}

return JsonResponse(content)

 

说明:

bootstarp-table默认只支持按单列排序,默认打开页面,请求表数据时,会附加提供以下参数:

order=asc&offset=0&limit=pageSize

 

或者如下(添加了搜索框的情况下)

search=&order=asc&offset=0&limit=pageSize

 

search:前端输入的搜索内容

order:排序方式,asc - 升序 desc - 降序

sort:需要排序的列

offset:偏移

limit:限制查询返回记录数,即每页记录数

 

如下,我们可以通过limit和offset获取要查询要查询页面的索引(索引从1开始)

page_size =  int(params.get('limit'))  # 每页记录数

offset = int(params.get('offset'))

page_index =  offset // page_size + 1  # 第几页数据

新增记录

def add_role(request):

'''

新增角色

   '''

if request.method == 'POST':

try:

           params = request.POST

           creater = str(request.user)

           role_name = params.get('roleName')      # 资源名称

role_desc = params.get('roleDesc')      # 资源描述

create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

 

# 验证数据合法性

if not role_name:

               content = {'msg':'新增角色失败',  'success':'false', 'reason': '角色名称不能为空'}

return JsonResponse(content)

 

           role_obj = Role(name=role_name,

remark=role_desc,

is_enable=1,

creater = creater,

create_time=create_time)

           role_obj.save()

           data = {'id':role_obj.id, 'name':role_name, 'remark':role_desc, 'is_enable':'', 'creater':str(creater), 'create_time':create_time, 'modifier':'-', 'modify_time':'-' }

           content = {'data':data, 'msg':'新增角色成功', 'success':'true', 'reason':''}

except Exception as e:

           logger.error('adding role failed: %s' % e)

           content = {'data':{}, 'msg':'新增角色失败',  'success':'false', 'reason': '%s' % e}

else:

       logger.error('only post method allowed for adding role data')

       content = {'data':{}, 'msg':'新增角色失败',  'success':'false', 'reason': 'only get method allowed for adding role data'}

return JsonResponse(content)

 

修改记录

 

def update_role(request):

'''

修改角色

   '''

if request.method == 'POST':

try:

           params = request.POST

           modifier = str(request.user)

           id = params['id']

           role_name = params['roleName']      # 资源名称

role_desc = params['roleDesc']      # 资源描述

modify_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

 

# 数据合法性验证

if not Role.objects.exclude(id=id).exists():

return JsonResponse({'msg':'修改失败', 'success':'false',  'reason': '角色不存在'})

 

# 更新数据

obj = Role.objects.get(id=id)

           obj.name = role_name

           obj.remark = role_desc

           obj.modify_time = modify_time

           obj.modifier = modifier

           obj.save()

 

           data = { 'name':role_name, 'remark':role_desc, 'modify_time':modify_time, 'modifier':modifier}  # 返回需要更新的数据,以便页面更新对应行信息

content = {'msg':'修改成功', 'data':data, 'success':'true', 'reason':''}

except Exception as e:

           logger.error('updating role failed: %s' % e)

           content = {'msg':'修改失败', 'data':{}, 'success':'false', 'reason': '%s' % e}

else:

       logger.error('only post method allowed for updating role')

       content = {'msg':'修改失败', 'data':{}, 'success':'false', 'reason': 'only post method allowed for updating role'}

return JsonResponse(content)

 

删除记录

def delete_role(request):

'''

删除角色

   '''

 

if request.method == 'POST':

try:

           params = request.POST

           id_list = eval(params.get('idArray') + ",") # 如果不加逗号,前端只传递一个参数时,这里获取到的id_list为单个整数值

 

mark = True

reason = ''

try:

with transaction.atomic():

for id in id_list:

                       role = Role.objects.filter(id=id)

if role.exists():

                           role.delete()

except Exception as e:

               reason = 'deleting role failed: %s' % e

               logger.error(reason)

               mark = False

 

           if mark:

return JsonResponse({'msg':'删除成功', 'success':'true',  'reason': ''})

else:

return JsonResponse({'msg':'删除失败', 'success':'false',  'reason': '%s' % reason})

except Exception as e:

           logger.error('deleting role failed: %s' % e)

           content = {'msg':'删除失败', 'success':'false', 'reason': '%s' % e}

else:

       logger.error('only post method allowed for deleting role')

       content = {'msg':'删除失败', 'success':'false', 'reason': 'only post method allowed for deleting role'}

return JsonResponse(content)

 

 

  1. 3.   参考链接

http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/

目录
相关文章
|
2月前
|
开发框架 前端开发 JavaScript
使用JavaScript、jQuery和Bootstrap构建待办事项应用
使用JavaScript、jQuery和Bootstrap构建待办事项应用
15 0
|
6月前
|
JSON 前端开发 数据格式
bootstrap table表格的点击详情按钮操作
bootstrap table表格的点击详情按钮操作
51 1
|
6月前
|
前端开发
表格插件-bootstrap table的隔行换色
表格插件-bootstrap table的隔行换色
69 0
|
6月前
|
前端开发 JavaScript
表格插件-bootstrap table的表内查看编辑删除
表格插件-bootstrap table的表内查看编辑删除
48 0
|
1天前
|
前端开发
BootStrap 5 保姆级教程(三):表格 & 图片
BootStrap 5 保姆级教程(三):表格 & 图片
|
5天前
|
机器学习/深度学习 前端开发 自动驾驶
【视频】什么是Bootstrap自抽样及应用R语言线性回归预测置信区间实例|数据分享
【视频】什么是Bootstrap自抽样及应用R语言线性回归预测置信区间实例|数据分享
11 2
|
2月前
|
开发框架 前端开发 JavaScript
使用React、Redux和Bootstrap构建社交媒体应用
使用React、Redux和Bootstrap构建社交媒体应用
15 0
|
6月前
|
JSON 前端开发 数据库
Bootstrap Table使用教程(请求json数据渲染表格)
Bootstrap Table使用教程(请求json数据渲染表格)
80 0
|
6月前
|
前端开发
bootstrap table+layer实现一个表格删除
bootstrap table+layer实现一个表格删除
23 0
|
6月前
|
前端开发
bootstrap table表格去掉排序箭头
bootstrap table表格去掉排序箭头
56 2