bootstrap-table中使用bootstrap-switch开关按钮

3 篇文章 0 订阅
2 篇文章 0 订阅

实现效果
在这里插入图片描述

引入插件文件
插件地址

<script src="/static/plugin/bootstrap-switch/js/bootstrap-switch.min.js"></script>

<link rel="stylesheet" href="/static/plugin/bootstrap-switch/css/bootstrap-switch.min.css"/>

BootStrapTable表格数据展示

function initTables(){
	let cols = [{
		checkbox: true,
	},{
		title: "更新时间",
		field: "updateTime",
		align: 'center'
	},{
		title: "是否热门",
		field: "isHot",
		align: 'center',
		formatter: function (value, row, index) {
			//【0-否、1-是】[row.UUID 每行的唯一编码,后端查询字段对应]
			let swState = value == 1 ? true : false;
			return '<input type="checkbox" name="isEnableCk" '+(swState ? "checked" : "")+' value="'+row.UUID+'"/>';
		}
	}];
	
	// bootstrap-table的各种事件操作对象
	let methodCfg = {
	};
	
	//table 配置项(列表初始化数据展示)
	let tableOptions = {
		tableId: "TestTables",
		reqUrl: '/test/getTestList',
		sortName: "testToolbar",
		queryParams: function (params) {
			let temp = {
				limit: params.limit,      //页面大小
				offset: params.offset,    //页码
				order: params.order,      //排位命令(desc,asc)
				title: $('#title').val(), //搜索框条件
			};
			return temp;
		},
		singleSelect: false,
		detailView: false,
		onLoadSuccess: function(){
			//是否热门开关方法
			$("[name='isEnableCk']").bootstrapSwitch({
				onText: '是',
				offText: '否',
				size : 'small'
			}).on('switchChange.bootstrapSwitch', function (event, state){
				//修改操作
				$.ajax({
					type: "post",
					dataType: "json",
					async: false,
					url: '/test/updateIsHot',
					data: {
						isHot: state ? 1 : 0,
						jobUUID: event.currentTarget.value //唯一编码
					},
					success: function(data) {
						$('#TestTables').bootstrapTable('refresh'); //Table页面刷新
					},
					error: function(xhr, error, exception){
						let errorMsg = xhr.responseText;
						openMsg("error","系统异常,"+errorMsg+",请联系管理员!");
					}
				});
			});
		}
	};

	//初始化服务器端分页表格
	initAsyncBSTable(tableOptions, cols, methodCfg);
}

自定义通用方法

/**
 * 初始化服务器端分页表格
 * @param tableId 表格ID
 * @param toolBarId 工具栏ID
 * @param url 请求后台的地址
 * @param columns 显示列
 * @param singleSelect 是否可以多选,如果不传此参数,则默认为可以多选
 * @param detailView 是否显示详细
 * @param methodCfg bootstrap-table的各种事件操作对象
 */
function initAsyncBSTable(options, columns, methodCfg){
	$('#' + options.tableId).bootstrapTable({
	    url: options.reqUrl,
	    toolbar: '#' + options.toolBarId,
	    columns: columns,
	    striped: true, //是否显示行间隔色
	    pagination: true, //是否显示分页(*)
	    search: false, //是否显示表格搜索,此搜索是客户端搜索,不会进服务端
	    sortable: false, //是否启用排序,
	    sortOrder: 'desc', //排序方式
	    cache: false, //是否使用缓存,默认为true
	    pageSize: 10,                       //每页的记录行数(*)
        pageList: [10, 25, 50, 100, 200, 500, 1000],        //可供选择的每页的行数(*)
		showColumns: typeof(options.showColumns) == "undefined" ? true : options.showColumns,                  //是否显示所有的列(toolbar 工具栏)
        clickToSelect: true,                //是否启用点击选中行
        idField: 'id',						//主键列
        uniqueId: "uuid",                     //每一行的唯一标识
        searchAlign: 'left',
        buttonsAlign: 'left',
		showRefresh: typeof(options.showRefresh) == "undefined" ? true : options.showRefresh,					//是否显示刷新按钮
        dataType: "json",					//期待返回数据类型
        singleSelect: options.singleSelect,			//是否可以多选
        detailView: options.detailView,
        sidePagination: 'server',	//设置分页方式,可选值为 'client' 或者 'server'。默认为'client'
        maintainSelected: true,		//设置为 true 在点击分页按钮或搜索按钮时,将记住checkbox的选择项
        paginationPreText: '上一页',
        paginationNextText: '下一页',
        queryParams: options.queryParams,
        onExpandRow: typeof(methodCfg) == "undefined" ? null :  methodCfg.expandRow,
		onLoadSuccess: options.onLoadSuccess,
	});
}

后端代码【Controller】

@Controller
@RequestMapping("/test")
public class BusTestController {
	private String errorMsg = "错误代码:1010";
	
	@Autowired
    private TestService testService ;

	/**
     * 查询列表
     * @param offset 唯一编码
     * @param limit 唯一编码
     * @param title 搜索栏
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getTestList", produces = "text/html;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getTestList(Integer offset, Integer limit, String title) throws Exception {
        Map<String, Object> resMap = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("pageNum", offset);
        params.put("pageSize", limit);
        params.put("title", title);
        try {
            resMap = testService.findTestList(params);
        } catch (Exception e) {
            throw new Exception(errorMsg, e);
        }
        return convertToJsonData(resMap);
    }

	/**
     * 修改是否热门
     * @param jobUUID 唯一编码
     * @param isHot 是否热门【0-否、1-是】
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateIsHot", produces = "text/html;charset=UTF-8", method = {RequestMethod.POST})
    @ResponseBody
    public String updateIsHot(int isHot, String jobUUID) throws Exception {
        boolean result = false;
        try {
            result = busAgileJobService.updateIsHot(isHot, jobUUID);
        } catch (Exception e) {
            throw new Exception(errorMsg,e);
        }
        return convertToJsonData(result);
    }
}

后端代码【接口】

public interface TestService {

    //查询列表
    Map<String, Object> findTestList(Map<String, Object> params) throws Exception;

    //修改是否热门
    boolean updateIsHot(int isHot, String jobUUID) throws Exception;
}

后端代码【接口实现】

@Service("testService")
public class TestServiceImpl implements TestService {

    @Resource(name = "daoSupport")
    private DaoSupport dao;

    /**
     * 查询列表
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> findTestList(Map<String, Object> params) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        int total = (Integer) dao.findForObject("TestMapper.findTestTotal", params);
        List<?> infos = (List<?>) dao.findForList("TestMapper.findTestList", params);
        result.put("total", total);
        result.put("rows", infos);
        return result;
    }

    /**
     * 修改是否热门
     * @param jobUUID 唯一编码
     * @param isHot 是否热门【0-否、1-是】
     * @return
     * @throws Exception
     */
    @Override
    public boolean updateIsHot(int isHot, String jobUUID) throws Exception {
        Map<String,Object> params = new HashMap<String, Object>();
        params.put("jobUUID", jobUUID);
        params.put("isHot", isHot);
        return (Integer) dao.update("TestMapper.updateIsHot", params) > 0;
    }
}

后端代码【Mybatis TestMapper.xml】

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="TestMapper" >

	<!-- 查询总数 -->
	<select id="findTestTotal" resultType="java.lang.Integer" parameterType="java.util.HashMap">
		select
			count(*)
		from t_bus_test t
		where t.isDel = 0
		<if test="title != null and title != ''">
			and t.title like CONCAT('%','${title}','%')
		</if>
	</select>

	<!-- 查询列表 -->
  	<select id="findTestList" resultType="java.util.HashMap" >
		select
	 		t.UUID, t.isHot, t.updateTime
		from t_bus_test t
		where t.isDel = 0
		<if test="title != null and title != ''">
			and t.title like CONCAT('%','${title}','%')
		</if>
		order by t.updateTime desc
		<if test="pageNum != null and pageSize != null">
			limit #{pageNum}, #{pageSize}
		</if>
  	</select>

	<!-- 修改是否热门 -->
	<update id="updateIsHot" parameterType="java.util.HashMap" >
		update t_bus_test set
			isHot = #{isHot}
		where UUID = #{jobUUID}
	</update>
</mapper>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值