search
HomeWeb Front-endBootstrap TutorialDetailed tutorial on dynamic table of BootStrapTable [with code]

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 '女';
            }
        }
    },
}

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>

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();

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"/>

 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: 见下文
    })
})

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
    });

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
       });
   }

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
   });
 },

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

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

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();
                }
            });
        }
    });
};

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]");
    }
 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
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
Breaking Down Bootstrap: What It Is and Why It MattersBreaking Down Bootstrap: What It Is and Why It MattersApr 14, 2025 am 12:05 AM

Bootstrapisafree,open-sourceCSSframeworkthatsimplifiesresponsiveandmobile-firstwebsitedevelopment.Itofferspre-styledcomponentsandagridsystem,streamliningthecreationofaestheticallypleasingandfunctionalwebdesigns.

Bootstrap: Making Web Design EasierBootstrap: Making Web Design EasierApr 13, 2025 am 12:10 AM

What makes web design easier is Bootstrap? Its preset components, responsive design and rich community support. 1) Preset component libraries and styles allow developers to avoid writing complex CSS code; 2) Built-in grid system simplifies the creation of responsive layouts; 3) Community support provides rich resources and solutions.

Bootstrap's Impact: Accelerating Web DevelopmentBootstrap's Impact: Accelerating Web DevelopmentApr 12, 2025 am 12:05 AM

Bootstrap accelerates web development, and by providing predefined styles and components, developers can quickly build responsive websites. 1) It shortens development time, such as completing the basic layout within a few days in the project. 2) Through Sass variables and mixins, Bootstrap allows custom styles to meet specific needs. 3) Using the CDN version can optimize performance and improve loading speed.

Understanding Bootstrap: Core Concepts and FeaturesUnderstanding Bootstrap: Core Concepts and FeaturesApr 11, 2025 am 12:01 AM

Bootstrap is an open source front-end framework, and its main function is to help developers quickly build responsive websites. 1) It provides predefined CSS classes and JavaScript plug-ins to facilitate the implementation of complex UI effects. 2) The working principle of Bootstrap relies on its CSS and JavaScript components to realize responsive design through media queries. 3) Examples of usage include basic usage, such as creating buttons, and advanced usage, such as custom styles. 4) Common errors include misspelling of class names and incorrectly introducing files. It is recommended to use browser developer tools to debug. 5) Performance optimization can be achieved through custom build tools, best practices include predefined using semantic HTML and Bootstrap

Bootstrap Deep Dive: Responsive Design & Advanced Layout TechniquesBootstrap Deep Dive: Responsive Design & Advanced Layout TechniquesApr 10, 2025 am 09:35 AM

Bootstrap implements responsive design through grid systems and media queries, making the website adapted to different devices. 1. Use a predefined class (such as col-sm-6) to define the column width. 2. The grid system is based on 12 columns, and it is necessary to note that the sum does not exceed 12. 3. Use breakpoints (such as sm, md, lg) to define the layout under different screen sizes.

Bootstrap Interview Questions: Land Your Dream Front-End JobBootstrap Interview Questions: Land Your Dream Front-End JobApr 09, 2025 am 12:14 AM

Bootstrap is an open source front-end framework for rapid development of responsive websites and applications. 1. It provides the advantages of responsive design, consistent UI components and rapid development. 2. The grid system uses flexbox layout, based on 12-column structure, and is implemented through classes such as .container, .row and .col-sm-6. 3. Custom styles can be implemented by modifying SASS variables or overwriting CSS. 4. Commonly used JavaScript components include modal boxes, carousel diagrams and folding. 5. Optimization performance can be achieved by loading only necessary components, using CDN, and compressing merge files.

Bootstrap & JavaScript Integration: Dynamic Features & FunctionalityBootstrap & JavaScript Integration: Dynamic Features & FunctionalityApr 08, 2025 am 12:10 AM

Bootstrap and JavaScript can be seamlessly integrated to give web pages dynamic functionality. 1) Use JavaScript to manipulate Bootstrap components, such as modal boxes and navigation bars. 2) Ensure jQuery loads correctly and avoid common integration problems. 3) Achieve complex user interaction and dynamic effects through event monitoring and DOM operations.

How to get the bootstrap search barHow to get the bootstrap search barApr 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.

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools