Home Web Front-end Bootstrap Tutorial Detailed tutorial on dynamic table of BootStrapTable [with code]

Detailed tutorial on dynamic table of BootStrapTable [with code]

Aug 20, 2019 pm 02:32 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do I need to use flexbox in the center of the Bootstrap picture? Do I need to use flexbox in the center of the Bootstrap picture? Apr 07, 2025 am 09:06 AM

There are many ways to center Bootstrap pictures, and you don’t have to use Flexbox. If you only need to center horizontally, the text-center class is enough; if you need to center vertically or multiple elements, Flexbox or Grid is more suitable. Flexbox is less compatible and may increase complexity, while Grid is more powerful and has a higher learning cost. When choosing a method, you should weigh the pros and cons and choose the most suitable method according to your needs and preferences.

How to get the bootstrap search bar How to get the bootstrap search bar Apr 07, 2025 pm 03:33 PM

How to use Bootstrap to get the value of the search bar: Determines the ID or name of the search bar. Use JavaScript to get DOM elements. Gets the value of the element. Perform the required actions.

How to do vertical centering of bootstrap How to do vertical centering of bootstrap Apr 07, 2025 pm 03:21 PM

Use Bootstrap to implement vertical centering: flexbox method: Use the d-flex, justify-content-center, and align-items-center classes to place elements in the flexbox container. align-items-center class method: For browsers that do not support flexbox, use the align-items-center class, provided that the parent element has a defined height.

How do I customize the appearance and behavior of Bootstrap's components? How do I customize the appearance and behavior of Bootstrap's components? Mar 18, 2025 pm 01:06 PM

Article discusses customizing Bootstrap's appearance and behavior using CSS variables, Sass, custom CSS, JavaScript, and component modifications. It also covers best practices for modifying styles and ensuring responsiveness across devices.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to resize bootstrap How to resize bootstrap Apr 07, 2025 pm 03:18 PM

To adjust the size of elements in Bootstrap, you can use the dimension class, which includes: adjusting width: .col-, .w-, .mw-adjust height: .h-, .min-h-, .max-h-

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

See all articles