Home > Web Front-end > JS Tutorial > body text

Explanation on using plug-ins in bootstraptable to implement table query, paging and sorting operations

PHPz
Release: 2018-10-13 16:43:46
Original
5608 people have browsed it

This article mainly introduces the use of bootstraptable plug-in to implement query, paging, and sorting operations of table records. Friends in need can refer to Bootstrap tutorial.

In business system development, querying, paging, sorting and other processing of table records are very common. In Web development, many powerful plug-ins can be used to meet the requirements and can be extremely efficient. Greatly improve development efficiency, this essay introduces bootstrap-table, which is a very famous open source table plug-in and is widely used in many projects. The Bootstrap-table plug-in provides a very rich set of attributes, which can implement query, paging, sorting, check boxes, setting display columns, Card view, master-slave table display, merge columns, internationalization processing and other processing functions, and the plug-in At the same time, it also provides some good extension functions, such as moving rows, moving column positions and other special functions. The plug-in can be set using the HTML5-based data-* attribute identifier, or it can be set using Javascript, which is very convenient. This essay introduces the application of bootstrap-table plug-in in my actual project, and summarizes the experience in dealing with problems encountered in related use.

1. Introduction to Bootstrap-table resources and usage

There are two ways for Bootstrap-Table to display data into tables, one is client mode, One is server mode.

The so-called client mode refers to loading the data to be displayed in the table in the server at one time, and then converting it into JSON format and transmitting it to the interface to be displayed. The client mode is relatively simple. It is Load the data at once and put it on the interface, and then automatically generate paging according to the number of records per page you set. When the second page is clicked, the data will be automatically loaded and no more requests will be sent to the server. At the same time, users can use its own search function to achieve full data search. This method can be used when the amount of data is small.

The so-called server mode refers to sending data to the server for query based on the set number of records per page and the current page number to be displayed, and then displaying it in the table. This method can dynamically load data according to user needs, saving server resources, but it cannot use its own full data search function.

Bootstrap-table is a plug-in developed based on Boosttrap, so when using it, you need to introduce Bootstrap scripts and styles.

If the relevant files are not introduced in our project, these style and script files need to be introduced, as shown below.

<link rel="stylesheet" href="bootstrap.min.css" rel="external nofollow" >
<script src="jquery.min.js"></script>
<script src="bootstrap.min.js"></script>
Copy after login

However, the above content must be available when we develop the project, so we still focus on the import files required to use this plug-in.

CSS file introduction

<link rel="stylesheet" href="bootstrap-table.css" rel="external nofollow" >
Copy after login

Script file introduction

<script src="bootstrap-table.js"></script>
<--汉化文件,放在 bootstrap-table.js 后面-->
<script src="bootstrap-table-zh-CN.js"></script>
Copy after login

Generally speaking, if we develop a system based on MVC, the CSS and JS codes are placed in BundleConfig. Initialized in cs, as shown below

The use of bootstrap-table in the page can be divided into two types. One is purely written in HTML5, and various attribute settings are specified through data-*. One is the HTML+JS method to achieve flexible settings.

If we initialize the HTML code using the HTML5 identifier, it is the following code.

<table data-toggle="table" data-url="data1.json">
 <thead>
  <tr>
   <th data-field="id">Item ID</th>
   <th data-field="name">Item Name</th>
   <th data-field="price">Item Price</th>
  </tr>
 </thead>
</table>
Copy after login

If we use JS code to initialize the table plug-in, then we only need to declare a table object in HTML, as shown in the following code.

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

Then the simple JS code initialization is as follows

$(&#39;#table&#39;).bootstrapTable({
 url: &#39;data1.json&#39;,
 columns: [{
  field: &#39;id&#39;,
  title: &#39;Item ID&#39;
 }, {
  field: &#39;name&#39;,
  title: &#39;Item Name&#39;
 }, {
  field: &#39;price&#39;,
  title: &#39;Item Price&#39;
 }, ]
});
Copy after login

However, in fact, the JS configuration function we use bootstrap-table is definitely much more complicated than this. The following interface effect is the data display of the actual table .

2. Detailed use of bootstrap-table

1) The entire JS attribute configuration

is in the picture above , we use JS to initialize the table content. The JS code is as follows

 var $table;
  //初始化bootstrap-table的内容
  function InitMainTable () {
   //记录页面bootstrap-table全局变量$table,方便应用
   var queryUrl = &#39;/TestUser/FindWithPager?rnd=&#39; + Math.random()
   $table = $(&#39;#grid&#39;).bootstrapTable({
    url: queryUrl,      //请求后台的URL(*)
    method: &#39;GET&#39;,      //请求方式(*)
    //toolbar: &#39;#toolbar&#39;,    //工具按钮用哪个容器
    striped: true,      //是否显示行间隔色
    cache: false,      //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
    pagination: true,     //是否显示分页(*)
    sortable: true,      //是否启用排序
    sortOrder: "asc",     //排序方式
    sidePagination: "server",   //分页方式:client客户端分页,server服务端分页(*)
    pageNumber: 1,      //初始化加载第一页,默认第一页,并记录
    pageSize: rows,      //每页的记录行数(*)
    pageList: [10, 25, 50, 100],  //可供选择的每页的行数(*)
    search: false,      //是否显示表格搜索
    strictSearch: true,
    showColumns: true,     //是否显示所有的列(选择显示的列)
    showRefresh: true,     //是否显示刷新按钮
    minimumCountColumns: 2,    //最少允许的列数
    clickToSelect: true,    //是否启用点击选中行
    //height: 500,      //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
    uniqueId: "ID",      //每一行的唯一标识,一般为主键列
    showToggle: true,     //是否显示详细视图和列表视图的切换按钮
    cardView: false,     //是否显示详细视图
    detailView: false,     //是否显示父子表
    //得到查询的参数
    queryParams : function (params) {
     //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
     var temp = { 
      rows: params.limit,       //页面大小
      page: (params.offset / params.limit) + 1, //页码
      sort: params.sort,  //排序列名 
      sortOrder: params.order //排位命令(desc,asc) 
     };
     return temp;
    },
    columns: [{
     checkbox: true, 
     visible: true     //是否显示复选框 
    }, {
     field: &#39;Name&#39;,
     title: &#39;姓名&#39;,
     sortable: true
    }, {
     field: &#39;Mobile&#39;,
     title: &#39;手机&#39;,
     sortable: true
    }, {
     field: &#39;Email&#39;,
     title: &#39;邮箱&#39;,
     sortable: true,
     formatter: emailFormatter
    }, {
     field: &#39;Homepage&#39;,
     title: &#39;主页&#39;,
     formatter: linkFormatter
    }, {
     field: &#39;Hobby&#39;,
     title: &#39;兴趣爱好&#39;
    }, {
     field: &#39;Gender&#39;,
     title: &#39;性别&#39;,
     sortable: true
    }, {
     field: &#39;Age&#39;,
     title: &#39;年龄&#39;
    }, {
     field: &#39;BirthDate&#39;,
     title: &#39;出生日期&#39;,
     formatter: dateFormatter
    }, {
     field: &#39;Height&#39;,
     title: &#39;身高&#39;
    }, {
     field: &#39;Note&#39;,
     title: &#39;备注&#39;
    }, {
     field:&#39;ID&#39;,
     title: &#39;操作&#39;,
     width: 120,
     align: &#39;center&#39;,
     valign: &#39;middle&#39;,
     formatter: actionFormatter
    }, ],
    onLoadSuccess: function () {
    },
    onLoadError: function () {
     showTips("数据加载失败!");
    },
    onDblClickRow: function (row, $element) {
     var id = row.ID;
     EditViewById(id, &#39;view&#39;);
    },
   });
  };
Copy after login

The configuration properties of the above JS code are basically commented out, which is relatively easy to understand.

2) Query and paging

The table data paging here uses server paging. Data records are returned from the server according to the search conditions, and the sorting method is used. The queryParams here The parameters are the parameters submitted to the server.

 //得到查询的参数
    queryParams : function (params) {
     //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
     var temp = { 
      rows: params.limit,       //页面大小
      page: (params.offset / params.limit) + 1, //页码
      sort: params.sort,  //排序列名 
      sortOrder: params.order //排位命令(desc,asc) 
     };
     return temp;
    },
Copy after login
Copy after login

In addition, we see that the URL address interface for returning data is FindWithPager. Let’s take a look at how this MVC controller method handles data return.

/// <summary>
  /// 根据条件查询数据库,并返回对象集合(用于分页数据显示)
  /// </summary>
  /// <returns>指定对象的集合</returns>
  public override ActionResult FindWithPager()
  {
   //检查用户是否有权限,否则抛出MyDenyAccessException异常
   base.CheckAuthorized(AuthorizeKey.ListKey);

   string where = GetPagerCondition();
   PagerInfo pagerInfo = GetPagerInfo();
   var sort = GetSortOrder();

   List<TestUserInfo> list = null;
   if (sort != null && !string.IsNullOrEmpty(sort.SortName))
   {
    list = baseBLL.FindWithPager(where, pagerInfo, sort.SortName, sort.IsDesc);
   }
   else
   {
    list = baseBLL.FindWithPager(where, pagerInfo);
   } 

   //Json格式的要求{total:22,rows:{}}
   //构造成Json的格式传递
   var result = new { total = pagerInfo.RecordCount, rows = list };
   return ToJsonContent(result);
  }
Copy after login

The above code processes two parts of object information, one is paging entity class information, and the other is sorting information, and then obtains records based on these conditions and returns something like
{total:22,rows:{ }}JSON data record in

format. ​ ​ ​

var result = new { total = pagerInfo.RecordCount, rows = list };
   return ToJsonContent(result);
Copy after login

The code to obtain the paging parameter information is as follows ​ ​

 /// <summary>
  /// 根据Request参数获取分页对象数据
  /// </summary>
  /// <returns></returns>
  protected virtual PagerInfo GetPagerInfo()
  {
   int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
   int pageSize = Request["rows"] == null ? 10 : int.Parse(Request["rows"]);

   PagerInfo pagerInfo = new PagerInfo();
   pagerInfo.CurrenetPageIndex = pageIndex;
   pagerInfo.PageSize = pageSize;
   return pagerInfo;
  }
Copy after login

The code to obtain the sorting parameter information is as follows

 /// <summary>
  /// 获取排序的信息
  /// </summary>
  /// <returns></returns>
  protected SortInfo GetSortOrder()
  {
   var name = Request["sort"];
   var order = Request["sortOrder"];
   return new SortInfo(name, order);
  }
Copy after login

最后就是具体实现具体条件、具体页码、具体排序条件下的数据记录了,这部分可以根据自己的要求实现逻辑,这里只是给出一个封装好的处理调用即可。

baseBLL.FindWithPager(where, pagerInfo, sort.SortName, sort.IsDesc);
Copy after login

实际情况下,我们列表的展示,一般需要使用不同的条件进行数据的查询的,虽然这个Bootstrap-table控件提供了一个默认的查询按钮,不过一般是在客户端分页的情况下使用,而且略显简单,我们一般使用自己查询条件进行处理,如下界面所示。

或者如下的

那么这样对于上面的js属性就需要调整下接受查询条件参数queryParams 了

 //得到查询的参数
    queryParams : function (params) {
     //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
     var temp = { 
      rows: params.limit,       //页面大小
      page: (params.offset / params.limit) + 1, //页码
      sort: params.sort,  //排序列名 
      sortOrder: params.order //排位命令(desc,asc) 
     };
     return temp;
    },
Copy after login
Copy after login

对于自定义查询条件,我们可以用下面的常规方式增加参数,如下所示

但是查询条件的参数我们不方便一一设置,我们想通过一种较为快捷的方式来处理,那么就需要对这个处理方式进行一个特别的修改了,首先添加一个扩展函数来处理表单的条件

 //自定义函数处理queryParams的批量增加
  $.fn.serializeJsonObject = function () {
   var json = {};
   var form = this.serializeArray();
   $.each(form, function () {
    if (json[this.name]) {
     if (!json[this.name].push) {
      json[this.name] = [json[this.name]];
     }
     json[this.name].push();
    } else {
     json[this.name] = this.value || &#39;&#39;;
    }
   });
   return json;
  }
Copy after login

然后我们就可以批量处理表单的查询条件了

 queryParams : function (params) {
     //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
     var temp = $("#ffSearch").serializeJsonObject();
     temp["rows"] = params.limit;      //页面大小
     temp["page"] = (params.offset / params.limit) + 1; //页码
     temp["sort"] = params.sort;       //排序列名
     temp["sortOrder"] = params.order;     //排位命令(desc,asc) 

     //特殊格式的条件处理
     temp["WHC_Age"] = $("#WHC_Age").val() + "~" + $("#WHC_Age2").val();
     temp["WHC_BirthDate"] = $("#WHC_BirthDate").val() + "~" + $("#WHC_BirthDate2").val();

     return temp;
    },
Copy after login

然后后端统一按照逻辑处理查询参数即可。

3)格式化输出函数及其他

对于上面JS的配置信息,我们再来回顾一下,例如对于数据转义函数,可以格式化输出的内容的,如下界面代码。

格式化的数据转义函数如下,主要就是根据内容进行格式化输出的JS函数,好像是需要放在一个文件内。

 //连接字段格式化
  function linkFormatter(value, row, index) {    
   return "<a href=&#39;" + value + "&#39; title=&#39;单击打开连接&#39; target=&#39;_blank&#39;>" + value + "</a>";
  }
  //Email字段格式化
  function emailFormatter(value, row, index) {
   return "<a href=&#39;mailto:" + value + "&#39; title=&#39;单击打开连接&#39;>" + value + "</a>";
  }
  //性别字段格式化
  function sexFormatter(value) {
   if (value == "女") { color = &#39;Red&#39;; }
   else if (value == "男") { color = &#39;Green&#39;; }
   else { color = &#39;Yellow&#39;; }

   return &#39;<p style="color: &#39; + color + &#39;">&#39; + value + &#39;</p>&#39;;
  }
Copy after login

另外,我们看到行记录的最后增加了几个操作按钮,方便对当前记录的查看、编辑和删除操作,如下效果图所示。

这部分我们也是通过格式化函数进行处理的

 //操作栏的格式化
  function actionFormatter(value, row, index) {
   var id = value;
   var result = "";
   result += "<a href=&#39;javascript:;&#39; class=&#39;btn btn-xs green&#39; onclick=\"EditViewById(&#39;" + id + "&#39;, view=&#39;view&#39;)\" title=&#39;查看&#39;><span class=&#39;glyphicon glyphicon-search&#39;></span></a>";
   result += "<a href=&#39;javascript:;&#39; class=&#39;btn btn-xs blue&#39; onclick=\"EditViewById(&#39;" + id + "&#39;)\" title=&#39;编辑&#39;><span class=&#39;glyphicon glyphicon-pencil&#39;></span></a>";
   result += "<a href=&#39;javascript:;&#39; class=&#39;btn btn-xs red&#39; onclick=\"DeleteByIds(&#39;" + id + "&#39;)\" title=&#39;删除&#39;><span class=&#39;glyphicon glyphicon-remove&#39;></span></a>";
   return result;
  }
Copy after login

如果我们需要双击弹出编辑界面的层,我们可以处理表格的双击事件,如下代码所示。

      onDblClickRow: function (row, $element) {
          var id = row.ID;
          EditViewById(id, &#39;view&#39;);
        },
Copy after login

如果我们需要设置行的不同的样式展示,可以通过增加rowStyle的JS处理函数即可,如下代码所示

       rowStyle: function (row, index) { //设置行的特殊样式
          //这里有5个取值颜色[&#39;active&#39;, &#39;success&#39;, &#39;info&#39;, &#39;warning&#39;, &#39;danger&#39;];
          var strclass = "";
          if (index == 0) {
            strclass = "warning";
          }
          return { classes: strclass }
        }
Copy after login

对于表格记录的获取,我们可以通过下面的代码进行获取:$table.bootstrapTable('getSelections')

      var rows = $table.bootstrapTable(&#39;getSelections&#39;);
      if (rows.length > 0) {
        ID = rows[0].ID;
      }
Copy after login

如果是多条记录的处理,例如删除记录

    //实现删除数据的方法
    function Delete() {
      var ids = "";//得到用户选择的数据的ID
      var rows = $table.bootstrapTable(&#39;getSelections&#39;);
      for (var i = 0; i < rows.length; i++) {
        ids += rows[i].ID + &#39;,&#39;;
      }
      ids = ids.substring(0, ids.length - 1);
      DeleteByIds(ids);
    }
Copy after login

如果需要设置显示列显示,如下界面所示

以及排序处理

这些需要在JS代码开启相关的属性即可。

还有就是一种CardView的卡片视图格式,如下所示。

另外一种是父子表的展开明细的格式,如下所示

 以上就是bootstrap-table插件在我实际项目中的应用情况,基本上对JS各个属性的使用进行了一些介绍了,具体的应用我们可以参考它的文档,获取对应属性、方法、事件的详细说明,这样我们就可以更加详细的应用这个插件的各种功能了。

The above is the detailed content of Explanation on using plug-ins in bootstraptable to implement table query, paging and sorting operations. 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