Boostrap-table.js+bootstrap-editable.js增删改查完整案例

先上效果图:
Boostrap-table.js+bootstrap-editable.js增删改查完整案例_第1张图片
Boostrap-table.js简单表格可视化可参考我的另外一篇博文:Boostrap-table.js的表格数据可视化 集成bootstrap-table-editable.js

该完整案例是典型的部门管理,通过ajax发出增删改查请求:

html代码:

<section class="panel">
                        <header class="panel-heading">
                            部门列表
                        header>
                        <div id="toolbar" style="margin: 10px">
                            <section class="panel">
                                <div class="panel-body">
                                    <form class="form-inline">
                                        <button id="remove" class="btn btn-danger" disabled>
                                            <i class="glyphicon glyphicon-trash">i> 删除
                                        button>
                                        <div class="form-group">
                                            <input  class="form-control" id="nameInp" placeholder="输入新建部门名" style="display: none">
                                        div>
                                        <div class="form-group"  >
                                            <select class="form-control" id="departSel"  style="display: none;">
                                            select>
                                        div>
                                        <a id="add" class="btn btn-success">
                                            <i class="glyphicon glyphicon-plus">i> 新建
                                        a>
                                        <a id="cancel" class="btn btn-warning" style="display:none">
                                            <i class="icon icon-remove-circle">取消i>
                                        a>
                                        <span class="remind">span>
                                    form>
                                div>
                            section>
                        div>
                        <table id="departTable">
                        table>
                    section>

至于js的引用得参考我另外篇博客

js代码

/**
 * Created by ASUS on 2016/5/31. 部门管理
 */
$table = $("#departTable");
$remove = $('#remove');
$(document).ready(function(){
    initDepartSelect();
    //表格初始化
    var oTable = new TableInit();
    oTable.Init();
    //查询
   /* $("#queryBtn").click(function(){
        $table.bootstrapTable('destroy');//表格销毁
        oTable.Init()
    });*/
    $("#add").click(function(){
        var name = $("#nameInp").val();
        var parentId =$("#departSel").val();
            parentId = parentId=="*"?"":parentId;
        var  $remind = $(".remind");
        if($(this).find("i").hasClass("adding")){//提交新建数据
            if(name==''){
                $remind.html(' 部门名不能为空!');
                return;
            }
            if(/(^\s+)|(\s+$)/g.test(name)){
                $remind.html(' 部门名不能输入空格!');
                return;
            }
            if(name.length>20){
                $remind.html(' 部门名不能超过20个字符!');
                return;
            }
  //博主封装的ajax方法,详见我另外一篇博客   http://blog.csdn.net/u010543785/article/details/52366495          
  $.postJSON(baseUrl+"department/add",'{"name":"'+name+'","parentdepartId":"'+parentId+'"}',function(data){
                if(data>0){
                    $("#departSel").css("display","none");
                    $("#departSel").val("*");
                    $("#nameInp").css("display","none");
                    $("#nameInp").val("");
                    $("#cancel").css("display", "none");
                    $remind.html('');
                    $("#add").html(' 新建');
                    $table.bootstrapTable('destroy');//表格销毁
                    oTable.Init();
                    $.gritter.add({
                        title: '提示',
                        text: '新建部门成功!',
                        sticky: false,
                        time: 2500
                    });
                    initDepartSelect();
                }else{
                    alert("新建部门失败,请联系技术人员!");
                }
            })
        }else {
            $("#nameInp").css("display", "block");
            $("#departSel").css("display", "block");
            $("#cancel").css("display", "inline-block");
            $("#nameInp").focus();
            $("#add").html(' 确认');
        }
    });
});
$("#cancel").click(function(){
    $("#departSel").css("display","none");
    $("#departSel").val("*");
    $("#nameInp").css("display","none");
    $("#nameInp").val("");
    $("#add").html(' 新建');
    $(".remind").html('');
    $(this).css("display","none");
});
var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $table.bootstrapTable({
            pagination: false,
            url: baseUrl + "department/queryAll",
            columns: [
                {
                    field: 'state',
                    checkbox: true
                }, {
                    title: '部门名',
                    field: 'name',
                    align: 'left',
                    formatter: spanFormatter,
                    sortable: true
                }, {
                    title: '上级部门名',
                    field: 'parentdepartName',
                    align: 'left',
                    formatter: nullFormatter,
                    sortable: true
                }, {
                    field: 'id',
                    title: '操作',
                    align: 'left',
                    events: operateEvents,
                    formatter: operateFormatter
                }
            ]
        });
    }
    return oTableInit;
}

//操作
window.operateEvents = {
    'click .edit': function (e, value, row, index) {
        index = index+1;//tr所在行
        var $row = $table.find("tbody tr:nth-child("+index+")");
        //各字段的编辑
        var $name = $row.find("td:nth-child(2) span");
        var  $parentdepartName= $row.find("td:nth-child(3) span");

        if($(this).hasClass("editting")){//编辑完成
            $(this).siblings("a").css("display","none");
            $(this).find("i").removeClass("glyphicon-ok");
            $(this).find("i").addClass("glyphicon-edit");
            $(this).removeClass("editting");
            $row.find(".editable").editable('toggleDisabled');//转成不可编辑状态

            row.name = $name.html();
            var parentId = $parentdepartName.attr("data-value");
            row.parentdepartId = parentId=="null"?"":parentId;

             //博主封装的ajax方法,详见我另外一篇博客   http://blog.csdn.net/u010543785/article/details/52366495
     $.putJSON(baseUrl+"department/update", JSON.stringify(row),function(data){//编辑请求  并返回值
                if(data==1) {
                    $.gritter.add({
                        title: '提示',
                        text: '编辑部门成功!',
                        sticky: false,
                        time: 2000,
                    });
                }else{
                    alert("编辑失败,请联系技术人员!");
                }
            });
        }else{//开始编辑
            $(this).siblings("a").css("display","inline-block");
            $row.find(".editable").editable('toggleDisabled');
            $(this).find("i").removeClass("glyphicon-edit");
            $(this).find("i").addClass("glyphicon-ok");
            $(this).addClass("editting");
            //变成可编辑状态
            $name.editable({//部门名
                validate: function(value) {
                    if(/(^\s+)|(\s+$)/g.test(value)){
                        return '部门名不能输入空格!';
                    }
                    if(value.length>20){
                        return '部门名不能超过20个字符!';
                    }
                    if($.trim(value) == '') return '部门名不能为空!';

                }
            });
            $parentdepartName.editable({//部门
                type:'select2',
                emptytext: '无上级',
                showbuttons: false,
                select2: {
                    width: '230px',
                    minimumInputLength: 0,
                    minimumResultsForSearch: -1,
                    id: function (e) {
                        return e.id;
                    },
                    ajax: {
                        url: baseUrl+"department/queryAll",
                        dataType: 'json',
                        data: function (term, page) {
                            return { query: term };
                        },
                        results: function (data, page) {
                            var datas =[{"id":"null","name":"无上级"}];
                            for(var i in data){
                                datas.push(data[i]);
                            }
                            return { results: datas };
                        }
                    },
                    formatResult: function (depart) {
                        return depart.name;
                    },
                    formatSelection: function (depart) {
                        $parentdepartName.attr("data-value",depart.id);
                        return depart.name;
                    },
                    initSelection: function (element, callback) {
                        /* if(element.val()==""){
                            return;
                        }
                     return $.get(baseUrl+"department/queryById/"+element.val(), {}, function (data) {
                            callback(data);
                        }, 'json'); *///added dataType
                    }
                }
            });
        }
    },
    'click .cancel': function (e, value, row, index) {//取消编辑
        index = index+1;//tr所在行
        var $row = $table.find("tbody tr:nth-child("+index+")");
        $row.find(".editable").editable('toggleDisabled');
        $(this).siblings("a").find("i").removeClass("glyphicon-ok");
        $(this).siblings("a").find("i").addClass("glyphicon-edit");
        $(this).siblings("a").removeClass("editting");
        $(this).css("display","none");
    }
};
//批量删除操作
$table.on('check.bs.table uncheck.bs.table ' +
    'check-all.bs.table uncheck-all.bs.table', function () {
    $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);
    // save your data, here just save the current page
    selections = getIdSelections();
    // push or splice the selections if you want to save all data selections
});
$table.on('expand-row.bs.table', function (e, index, row, $detail) {
    if (index % 2 == 1) {
        $detail.html('Loading from ajax request...');
        $.get('LICENSE', function (res) {
            $detail.html(res.replace(/\n/g, '
'
)); }); } }); $remove.click(function () { var ids = getIdSelections(); //博主封装的ajax方法,详见我另外一篇博客 http://blog.csdn.net/u010543785/article/details/52366495 $.putJSON(baseUrl+"department/deletes","["+ids.toString()+"]",function(data){ if(data>0){ $table.bootstrapTable('remove', { field: 'id', values: ids }); $.gritter.add({ title: '提示', text: '删除部门成功!', sticky: false, time: 2500 }); }else{ alert("删除失败,请联系技术人员!"); } }); $remove.prop('disabled', true); }); function getIdSelections() { return $.map($table.bootstrapTable('getSelections'), function (row) { return row.id }); } //---formatter 格式化返回td function spanFormatter(data) { return ""+data+""; } function nullFormatter(value, row) { if(value==""||value==null||value=="null") { return ""; } return ""+value+""; } function operateFormatter(value, row, index) { return [ '', '', ' ', '' ].join(''); } //初始化部门下拉框 function initDepartSelect() { //博主封装的ajax方法,详见我另外一篇博客 http://blog.csdn.net/u010543785/article/details/52366495 $.sanjiGetJSON(baseUrl + "department/queryAll", '', function (data) { $("#departSel").html(""); $("#departSel").append(''); for (var i = 0; i < data.length; i++) { $("#departSel").append(' + data[i].name + ''); } //$("#departSel").select2(); }); }

该部门管理并没有查询功能,附上

查询功能

的例子:


$(document).ready(function(){
    if(localStorage.getItem("rolesName")!="管理员"){//权限控制
        $("#add").remove();
    }
    //初始化下拉框
    initRolesSelect();
    //表格初始化
    var oTable = new TableInit();
    oTable.Init();
    //查询
    $("#queryBtn").click(function(){
        $table.bootstrapTable('destroy');//表格销毁
        oTable.Init()
    });
});


var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $table.bootstrapTable({
            pagination: true,
            url: baseUrl + "user/query",
            queryParams: oTableInit.queryParams,
            columns: [
                {
                    field: 'state',
                    checkbox: true
                }, {
                    title: '用户名',
                    field: 'username',
                    align: 'left',
                    formatter: spanFormatter,
                    sortable: true
                }, {
                    title: '真名',
                    field: 'longname',
                    align: 'left',
                    sortable: true,
                    formatter: nullFormatter
                }, {
                    title: '角色',
                    field: 'rolesName',
                    align: 'left',
                    sortable: true,
                    formatter: rolesFormatter
                }, {
                    title: '所在部门',
                    field: 'departName',
                    align: 'left',
                    formatter: departFormatter
                }, {
                    title: '最后一次登录',
                    field: 'logTime',
                    align: 'left',
                    sortable: true,
                    formatter: timeFormatter
                }, {
                    field: 'id',
                    title: '操作',
                    align: 'left',
                    events: operateEvents,
                    formatter: operateFormatter
                }
            ]
        });
    }
    //查询条件
     oTableInit.queryParams  = function(params){
        var temp={
            rolesId:$("#rolesSel").val()=="*"?null:$("#rolesSel").val(),
            departId:$("#departSel").val()=="*"?null:$("#departSel").val(),
            username:$("#usernameInp").val()==""?null:$("#usernameInp").val()
        }
        return temp;
    }
     return oTableInit;

    //一次性获取所有数据时responseHandler 这段代码不需要。 但是只获取单页数据时就需要该段代码提供总行数,以便显示分页信息
/*   oTableInit.responseHandler = function (res) {


        if (res != null) {
            return {
                "rows": res.rows, //查询到到单页里的数据
                "total": res.total //总行数(数据库里查询到的总记录数量)
            };

        } else {
            return {
                "rows": [],
                "total": 0
            };
        }

    }
    return oTableInit; */
}

上获取单页数据的page模型,如一次性获取所有数据则不需要该模型

/**
 * 封装分页数据
 * @param 
 */

public class Page {
    private List rows;//数据
    private int total;//总行数
    public List getRows() {
        return rows;
    }
    public void setRows(List rows) {
        this.rows = rows;
    }
    public int computeTotal(int totalRows,int size) {
        if(totalRows==0){
            return 1;
        }
            return  (int) (totalRows % size == 0 ? totalRows / size
                : totalRows / size + 1);
    }
    public int getTotal() {
        return total;
    }
    public void setTotal(int total) {
        this.total = total;
    }

上java后台代码, springmvc获取单页数据的controller

/**
     * 
     * @param @param psUser ps用户名
     * @param @param psLongname ps用户真名
     * @param @param departId  部门ID
     * @param @return   
     * @return List  
     * @throws
     * @date 2016年6月3日
     */
    @RequestMapping(value = "/queryByPage", method = RequestMethod.GET)
    public @ResponseBody
    Page query(@RequestParam String pageNumber,
            @RequestParam String pageSize,@RequestParam String daterange, @RequestParam String recordUser, @RequestParam String caller,@RequestParam String sort) {
        Page page = new Page();
        int no = pageNumber == null ? 10 : Integer.parseInt(pageNumber);
        int size = pageSize == null ? 10 : Integer.parseInt(pageSize);
        List psRecords = null;
        HashMap map = new HashMap();
        try {
             String[] dateranges  = new String(daterange.getBytes("iso8859-1"),"UTF-8").split(" ");
             String startDate="",endDate = "";
             if(dateranges.length>1){
                 startDate =  dateranges[0];
                 endDate =  dateranges[2];
             }
             map.put("startDate", startDate);
             map.put("endDate", endDate);
             map.put("recordUser", new String(recordUser.getBytes("iso8859-1"),"UTF-8"));
             map.put("caller", new String(caller.getBytes("iso8859-1"),"UTF-8"));
             psRecords = psRecordService.queryByPage(startDate,endDate,new String(recordUser.getBytes("iso8859-1"),"UTF-8")
            ,new String(caller.getBytes("iso8859-1"),"UTF-8"),size*(no-1),size,sort);

            //返回的数据初始化page
            page.setRows(psRecords);
            page.setTotal(psRecordService.count(map));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return page;
    }

对代码如有问题,私信我~

你可能感兴趣的:(web)