Detailed tutorial on dynamic table of BootStrapTable [with code]

angryTom
Release: 2020-05-15 09:18:34
Original
11427 people have browsed it

Detailed tutorial on dynamic table of BootStrapTable [with code]

This article will introduce how to use the bootstrap table plug-in to implement dynamic tables.

Recommended tutorial: Bootstrap tutorial

## When we build BootStrapTable (hereinafter referred to as: BsTable), the columns Parameters are stored as the contents of table columns. Our requirement is to dynamically generate the contents of columns parameters based on the returned data. This generates dynamic tables.

columns parameter format: similar to the following

columns: {
    {
        field: 'Id',
        title: '编号',
    },{
        field: 'name',
        title: '名称',
    },{
        field: 'sex',
        title: '性别',
        //自定义方法
        formatter: function (value) {
            if (value == 1) {
                return '男';
            } else if (value == 2) {
                retuen '女';
            }
        }
    },
}
Copy after login

Requirement: Send an ajax request by clicking the button, and build a dynamic table based on the data returned by the request.

Button structure: setting click event

<button type="button" class="btn btn-primary" onclick="DataQuery.sqlExecute()">
    <i class="fa fa-check"></i> SQL语句执行
</button>
Copy after login

Click event writing: dataQuery.js (Note: This will be analyzed piece by piece,

The complete version will be posted at the end Code)

1. Get the html page element value

Since two parameters are needed to implement this function: SQL statement (sql ) connection information (connectInfo), so you must first obtain the values ​​​​of the two elements from the page: the class selector selects the element to obtain the corresponding value.

var sql = $(&#39;#sql&#39;).val();
var connectInfo = $(&#39;#connectInfo&#39;).val();
Copy after login

2. Select the page table element, send an ajax request, and build the BSTable

table element on the page: use beetl tags, Replace the reused html code with a line of code tags, which is convenient to use and easy to maintain.

<#table id="DataQueryTable"/>
Copy after login

 2.1 Ajax request parameter configuration

##ParametertypeurlcontentTypedataType datasuccesserrorDetailed code:
Meaning
Request type
Request link address
Format sent to the server
Format of received data
Data sent to the server
Called when the request is successful
Called when the request fails
$(&#39;#DataQueryTable&#39;).bootstrapTable({
    ajax: function (request) {
        $.ajax({
            type: "GET",
            url: Feng.ctxPath + "/dataQuery/list" + "/" + sql + "/" + connectInfo,
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            json: &#39;callback&#39;,
            success: 见下文
            error: 见下文
    })
})
Copy after login

2.2 The ajax request is successful, and the dynamic header is constructed based on the returned json data

2.2.1 Initialize custom dynamic header array

 //定义动态表头字段数组
    var dynamicHeader = [];
    //向数组中填入属性
    dynamicHeader.push({
        field: "state",
        check: true
    });
Copy after login

2.2.2 Dynamic header generation

  //针对返回的json数据,遍历json数据的key集合
   for (var i = 0; i<(Object.keys(json[0])).length; i++) {
       //获取对应索引的value值,将获取的值设置到动态表头字段中。
       var property = (Object.keys(json[0]))[i];
       dynamicHeader.push({
           "title": property,
           "field": property,
           //显示是否显示隐藏
           switchable: true,
           //是否开启排序
           sortable: true
       });
   }
Copy after login

We can view this code with browser F12 Specific content in Object.keys(json[0]): simulate a request/test.

## 2.2.3 Construct the table. The table must be destroyed before constructing the table, otherwise the last loaded content will be retainedDetailed tutorial on dynamic table of BootStrapTable [with code]

  $(&#39;#DataQueryTable&#39;).bootstrapTable(&#39;destroy&#39;).bootstrapTable({
       //得到的json数据,会根据columns参数进行对应赋值配置
       data: json,
       //Bstable工具导航条
       toolbar: &#39;#toolbar&#39;,
       //浏览器缓存,默认为true,设置为false避免页面刷新调用浏览器缓存
       cache: false,
       //是否显示行间隔色
       striped: true,
       //分页方式:client客户端分页,server服务端分页
       sidePagination: "client",
       //排序方式
       sortOrder: "desc",
       //每页记录行数
       pageSize: 25,
       //初始化加载第一页
       pageNumber: 1,
       //可供选择的每页行数
       pageList: "[25, 50, 100, All]",
       //是否显示切换按钮
       showToggle: true,
       //是否显示所有的列
       showColumns: true,
       //是否显示导出按钮(下篇文章将会提到)
       showExport: true,
       //导出数据类型(下篇文章将会提到)
       exportDataType: "basic",
       //是否显示分页
       pagination: true,
       //是否启用全匹配搜索,否则为模糊搜索
       strictSearch: true,
       //开启搜索
       search: true,
       //自定义所生成的动态表头放入,结合上述json数据,实现表格数据内容的构建
       columns: dynamicHeader
   });
 },
Copy after login

 2.3 Ajax request Failure, pop-up window reports error message, page reloads

error: function () {
    alert("SQL查询错误,请输入正确的SQL语句!");
    location.reload();
}
Copy after login

Complete js code

/**
 *  BsTable动态表格生成
 */
DataQuery.sqlExecute = function (){

    var sql = $(&#39;#sql&#39;).val();
    var connectInfo = $(&#39;#connectInfo&#39;).val();

    $(&#39;#DataQueryTable&#39;).bootstrapTable({
        ajax: function (request) {
            $.ajax({
                type: "GET",
                url: Feng.ctxPath + "/dataQuery/list" + "/" + sql + "/" + connectInfo,
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                json: &#39;callback&#39;,
                success: function (json) {

                    var dynamicHeader = [];
                    dynamicHeader.push({
                        field: "state",
                        check: true
                    });

                    for (var i = 0; i<(Object.keys(json[0])).length; i++) {
                        var property = (Object.keys(json[0]))[i];
                        //console.log(property);
                        dynamicHeader.push({
                            "title": property,
                            "field": property,
                            switchable: true,
                            sortable: true
                        });
                    }

                    //console.log(Object.keys(json[0]));

                    $(&#39;#DataQueryTable&#39;).bootstrapTable(&#39;destroy&#39;).bootstrapTable({
                        data: json,
                        toolbar: &#39;#toolbar&#39;,
                        cache: false,
                        striped: true,
                        sidePagination: "client",
                        sortOrder: "desc",
                        pageSize: 25,
                        pageNumber: 1,
                        pageList: "[25, 50, 100, All]",
                        showToggle: true,
                        showColumns: true,
                        showExport: true,
                        exportDataType: "basic",
                        pagination: true,
                        strictSearch: true,
                        search: true,
                        columns: dynamicHeader
                    });
                },
                error: function () {
                    alert("SQL查询错误,请输入正确的SQL语句!");
                    location.reload();
                }
            });
        }
    });
};
Copy after login

3. Test the dynamic table generation results

3.1 The test is divided into two parts. First, obtain the json data obtained by the request, and simulate the request to obtain 100 pieces of data

@RequestMapping(value = "/test")
    @ResponseBody
    public Object test(){
        return iDataQueryService.windQuery("SELECT TOP 100 [OBJECT_ID]\n" +
                "      ,[S_INFO_WINDCODE]\n" +
                "      ,[S_CON_WINDCODE]\n" +
                "      ,[S_CON_INDATE]\n" +
                "      ,[S_CON_OUTDATE]\n" +
                "      ,[CUR_SIGN]\n" +
                "      ,[OPDATE]\n" +
                "      ,[OPMODE]\n" +
                "  FROM [WIND].[db_datareader].[AINDEXMEMBERS]");
    }
Copy after login
 3.2 View the json data returned by the request

Detailed tutorial on dynamic table of BootStrapTable [with code]## 3.3 Test dynamic table generation

The above request can return data normally, but what about the dynamic BSTable we built through ajax request? The request is: SQL statement/link information, and the ajax request returns json data, which is consistent with the above request.

Check out our dynamic table generation status:

Detailed tutorial on dynamic table of BootStrapTable [with code]

Detailed tutorial on dynamic table of BootStrapTable [with code]

Bingo, So far, the BootStrapTable dynamic table function has been implemented.

The above is the detailed content of Detailed tutorial on dynamic table of BootStrapTable [with code]. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!