0

我使用bootstrap-table,由于数据是从后端返回的对象中拿到其中的一个list来展示的,所以不能直接在js配置里写接口和返回数据,我默认ajax请求到数据之后如何默认渲染到table中,我看网上教程大多数都是动态从服务器渲染的。

希望有大神可以教一套靠谱的可以获取到ajax等数据并渲染到页面的方案!!!!!!!!!

这里假设我已经拿到数据的数组 projectList

clipboard.png

var $table =  $("#projectTable"),
    $remove = $('#remove'),
    selections = [];
function initTable() {
    $table.bootstrapTable({
        height: getHeight(),
        data:data1,
        method:'get',
        url:"/",
        toolbar:'#toolbar',
        cache: false, // 设置为 false 禁用 AJAX 数据缓存, 默认为true
        striped: true,  //表格显示条纹,默认为false
        pagination: true, // 在表格底部显示分页组件,默认false
        pageList: [10, 20, 50, 100, 'ALL'], // 设置页面可以显示的数据条数
        pageSize: 10, // 页面数据条数
        pageNumber: 1, // 首页页码
        sidePagination: 'client', // 设置为服务器端分页
        /*queryParams: function (params) { // 请求服务器数据时发送的参数,可以在这里添加额外的查询参数,返回false则终止请求
            return {
                pageSize: params.limit, // 每页要显示的数据条数
                offset: params.offset, // 每页显示数据的开始行号
                sort: params.sort, // 要排序的字段
                sortOrder: params.order, // 排序规则
                dataId: $("#dataId").val() // 额外添加的参数
            }
        },*/
        sortName: 'id', // 要排序的字段
        sortOrder: 'desc', // 排序规则,
        search: true,                       //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大
        strictSearch: true,
        showColumns: true,                  //是否显示所有的列
        showRefresh: true,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "ID",                     //每一行的唯一标识,一般为主键列
        // showToggle:true,                    //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,                   //是否显示父子表
        showExport: true,
        exportDataType: 'all',
        exportTypes:[ 'csv','excel','pdf'],  //导出文件类型
        columns: [
            {
                checkbox: true, // 显示一个勾选框
                align: 'center' // 居中显示
            }, {
                field: 'statusOrder', // 返回json数据中的name
                title: '流程顺序', // 表格表头显示文字
                align: 'center', // 左右居中
                valign: 'middle', // 上下居中
                sortable: true,
                /*editable: {
                    type: 'text',
                    title: '流程顺序',
                    validate: function (value) {
                        value = $.trim(value);
                        if (!value) {
                            return '流程顺序不能为空';
                        }
                        if (!/^\+?[1-9][0-9]*$/.test(value)) {
                         return '流程顺序必须为大于0的整数.'
                         }
                    }
                },*/
            }, {
                field: 'statusName',
                title: '流程名称',
                align: 'center',
                valign: 'middle',
                sortable: true,
                /*editable: {
                    type: 'text',
                    title: '流程名称',
                    validate: function (value) {
                        value = $.trim(value);
                        if (!value) {
                            return '流程名称不能为空';
                        }
                        var data = $table.bootstrapTable('getData'),
                            index = $(this).parents('tr').data('index');
                        console.log(data[index]);
                        return '';
                    }
                },*/
            }, {
                field: 'statusInfo',
                title: '流程说明',
                align: 'center',
                valign: 'middle',
                sortable: true,
                /*editable: {
                    type: 'text',
                    title: '流程说明',
                    validate: function (value) {
                        value = $.trim(value);
                        if (!value) {
                            return '流程说明不能为空';
                        }
                        var data = $table.bootstrapTable('getData'),
                            index = $(this).parents('tr').data('index');
                        console.log(data[index]);
                        return '';
                    }
                },*/
            }, {
                field: 'formModels',
                title: '流程需填写表单',
                align: 'center',
                valign: 'middle',
                /*editable: {
                    type: 'text',
                    title: '流程需填写表单',
                    validate: function (value) {
                        value = $.trim(value);
                        if (!value) {
                            return 'This field is required';
                        }
                        if (!/^\$/.test(value)) {
                            return 'This field needs to start width $.'
                        }
                        var data = $table.bootstrapTable('getData'),
                            index = $(this).parents('tr').data('index');
                        console.log(data[index]);
                        return '';
                    }
                },*/
            }, {
                field: 'tableModels',
                title: '流程需填写表格',
                align: 'center',
                valign: 'middle',
                /*editable: {
                    type: 'text',
                    title: '流程需填写表格',
                    validate: function (value) {
                        value = $.trim(value);
                        if (!value) {
                            return 'This field is required';
                        }
                        if (!/^\$/.test(value)) {
                            return 'This field needs to start width $.'
                        }
                        var data = $table.bootstrapTable('getData'),
                            index = $(this).parents('tr').data('index');
                        console.log(data[index]);
                        return '';
                    }
                },*/
            },{
                title: "操作",
                align: 'center',
                valign: 'middle',
                width: 160, // 定义列的宽度,单位为像素px
                formatter: function (value, row, index) {
                    return '<button class="btn btn-primary btn-sm" onclick="del(\'' + row.field + value + '\')">删除</button>';
                }
            }
        ],
        onLoadSuccess: function(){  //加载成功时执行
            console.info("加载成功");
        },
        onLoadError: function(){  //加载失败时执行
            console.info("加载数据失败");
        }
        /*columns: [
         [
         {
         field: 'state',
         checkbox: true,
         rowspan: 1,
         align: 'center',
         valign: 'middle'
         }, {
         title: 'Item ID',
         field: 'id',
         rowspan: 1,
         align: 'center',
         valign: 'middle',
         sortable: true,
         footerFormatter: totalTextFormatter
         }, {
         title: 'Item Detail',
         field: 'detail',
         colspan: 3,
         rowspan: 1,
         align: 'center'
         }
         ],
         /!*[
         {
         field: 'name',
         title: 'Item Name',
         sortable: true,
         editable: true,
         footerFormatter: totalNameFormatter,
         align: 'center'
         }, {
         field: 'price',
         title: 'Item Price',
         sortable: true,
         align: 'center',
         editable: {
         type: 'text',
         title: 'Item Price',
         validate: function (value) {
         value = $.trim(value);
         if (!value) {
         return 'This field is required';
         }
         if (!/^\$/.test(value)) {
         return 'This field needs to start width $.'
         }
         var data = $table.bootstrapTable('getData'),
         index = $(this).parents('tr').data('index');
         console.log(data[index]);
         return '';
         }
         },
         footerFormatter: totalPriceFormatter
         }, {
         field: 'operate',
         title: 'Item Operate',
         align: 'center',
         events: operateEvents,
         formatter: operateFormatter
         }
         ]*!/
         ]*/
    });
    // sometimes footer render error.
    setTimeout(function () {
        $table.bootstrapTable('resetView');
    }, 200);
    $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>'));
            });
        }
    });
    $table.on('all.bs.table', function (e, name, args) {
        console.log(name, args);
    });
    $remove.click(function () {
        var ids = getIdSelections();
        $table.bootstrapTable('remove', {
            field: 'id',
            values: ids
        });
        $remove.prop('disabled', true);
    });
    $(window).resize(function () {
        $table.bootstrapTable('resetView', {
            height: getHeight()
        });
    });
}

function getIdSelections() {
    return $.map($table.bootstrapTable('getSelections'), function (row) {
        return row.id
    });
}

function responseHandler(res) {
    $.each(res.rows, function (i, row) {
        row.state = $.inArray(row.id, selections) !== -1;
    });
    return res;
}

function detailFormatter(index, row) {
    var html = [];
    $.each(row, function (key, value) {
        html.push('<p><b>' + key + ':</b> ' + value + '</p>');
    });
    return html.join('');
}

function operateFormatter(value, row, index) {
    return [
        '<a class="like" href="javascript:void(0)" title="Like">',
        '<i class="glyphicon glyphicon-heart"></i>',
        '</a>  ',
        '<a class="remove" href="javascript:void(0)" title="Remove">',
        '<i class="glyphicon glyphicon-remove"></i>',
        '</a>'
    ].join('');
}

window.operateEvents = {
    'click .like': function (e, value, row, index) {
        alert('You click like action, row: ' + JSON.stringify(row));
    },
    'click .remove': function (e, value, row, index) {
        $table.bootstrapTable('remove', {
            field: 'id',
            values: [row.id]
        });
    }
};

function totalTextFormatter(data) {
    return 'Total';
}

function totalNameFormatter(data) {
    return data.length;
}

function totalPriceFormatter(data) {
    var total = 0;
    $.each(data, function (i, row) {
        total += +(row.price.substring(1));
    });
    return '$' + total;
}

function getHeight() {
    return $(window).height() - $('h1').outerHeight(true);
}
function del(field,values) {
    $("#projectTable").bootstrapTable('remove',filed,values);
}
function delMore(id) {
    $("#projectTable").bootstrapTable('removeByUniqueId    ',id);
}
$(function () {
    var scripts = [
            'https://cdn.bootcss.com/bootstrap-table/1.12.1/bootstrap-table.min.js',
            // location.search.substring(1) || 'https://cdn.bootcss.com/bootstrap-table/1.12.1/bootstrap-table.min.js',
            'https://cdn.bootcss.com/bootstrap-table/1.12.1/extensions/export/bootstrap-table-export.min.js',
            // 'http://rawgit.com/hhurz/tableExport.jquery.plugin/master/tableExport.js',
            'https://cdn.bootcss.com/bootstrap-table/1.12.1/extensions/editable/bootstrap-table-editable.min.js',
            'https://cdn.bootcss.com/x-editable/1.5.1/bootstrap3-editable/js/bootstrap-editable.min.js'
        ],
        eachSeries = function (arr, iterator, callback) {
            callback = callback || function () {
                };
            if (!arr.length) {
                return callback();
            }
            var completed = 0;
            var iterate = function () {
                iterator(arr[completed], function (err) {
                    if (err) {
                        callback(err);
                        callback = function () {
                        };
                    }
                    else {
                        completed += 1;
                        if (completed >= arr.length) {
                            callback(null);
                        }
                        else {
                            iterate();
                        }
                    }
                });
            };
            iterate();
        };

    eachSeries(scripts, getScript, initTable);
});

function getScript(url, callback) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.src = url;
    var done = false;
    // Attach handlers for all browsers
    script.onload = script.onreadystatechange = function () {
        if (!done && (!this.readyState ||
            this.readyState == 'loaded' || this.readyState == 'complete')) {
            done = true;
            if (callback)
                callback();

            // Handle memory leak in IE
            script.onload = script.onreadystatechange = null;
        }
    };

    head.appendChild(script);

    // We handle everything using the script element injection
    return undefined;
}
//cookie 封装 获取 cookie
function getCookie(name) {
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

撰写答案