1. 程式人生 > >Boostrap-table.js+bootstrap-editable.js增刪改查完整案例

Boostrap-table.js+bootstrap-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(' <i class="icon icon-info-sign">部門名不能為空!</i>');
                return;
            }
            if(/(^\s+)|(\s+$)/g.test(name)){
                $remind.html(' <i class="icon icon-info-sign">部門名不能輸入空格!</i>');
                return;
            }
            if(name.length>20){
                $remind.html(' <i class="icon icon-info-sign">部門名不能超過20個字元!</i>');
                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('<i class="glyphicon glyphicon-plus"></i> 新建');
                    $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('<i class="glyphicon glyphicon-ok-circle adding"></i> 確認');
        }
    });
});
$("#cancel").click(function(){
    $("#departSel").css("display","none");
    $("#departSel").val("*");
    $("#nameInp").css("display","none");
    $("#nameInp").val("");
    $("#add").html('<i class="glyphicon glyphicon-plus"></i> 新建');
    $(".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, '<br>'));
        });
    }
});
$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 "<span style='cursor:pointer'>"+data+"</span>";
}
function nullFormatter(value, row) {
    if(value==""||value==null||value=="null") {
        return "<span style='cursor:pointer' data-value='"+row.parentdepartId+"'></span>";
    }
    return "<span style='cursor:pointer' data-value='"+row.parentdepartId+"'>"+value+"</span>";
}
function operateFormatter(value, row, index) {
    return [
        '<a class="edit" href="javascript:void(0)" title="編輯">',
        '<i class="glyphicon glyphicon-edit"></i>',
        '</a>  ',
        '<a class="cancel" href="javascript:void(0)" title="取消編輯" style="display:none">',
        '<i class="glyphicon glyphicon-remove"></i>',
        '</a>'
    ].join('');
}
//初始化部門下拉框
function initDepartSelect() {
 //博主封裝的ajax方法,詳見我另外一篇部落格   http://blog.csdn.net/u010543785/article/details/52366495
  $.sanjiGetJSON(baseUrl + "department/queryAll", '', function (data) {

            $("#departSel").html("");
            $("#departSel").append('<option value="*">請選擇上級部門</option>');
            for (var i = 0; i < data.length; i++) {
                $("#departSel").append('<option value="' + data[i].id + '">' + data[i].name + '</option>');
            }
            //$("#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 <T>
 */

public class Page<T> {
    private List<T> rows;//資料
    private int total;//總行數
    public List<T> getRows() {
        return rows;
    }
    public void setRows(List<T> 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<psRecord>  
     * @throws
     * @date 2016年6月3日
     */
    @RequestMapping(value = "/queryByPage", method = RequestMethod.GET)
    public @ResponseBody
    Page<psRecord> query(@RequestParam String pageNumber,
            @RequestParam String pageSize,@RequestParam String daterange, @RequestParam String recordUser, @RequestParam String caller,@RequestParam String sort) {
        Page<psRecord> page = new Page<psRecord>();
        int no = pageNumber == null ? 10 : Integer.parseInt(pageNumber);
        int size = pageSize == null ? 10 : Integer.parseInt(pageSize);
        List<psRecord> psRecords = null;
        HashMap<String,String> map = new HashMap<String,String>();
        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;
    }

對程式碼如有問題,私信我~