Home > php教程 > PHP开发 > body text

Bootstrap table usage analysis

高洛峰
Release: 2016-12-08 10:02:52
Original
2140 people have browsed it

Learn some things in Jquery for a while and supplement and improve them. After all, sometimes they are not used.
This method is very useful. When using bootstrap table, select the value of the ID in the event of the currently selected node
In the current rows There is a lot of data, but I only need the value of id. At this time, the operation is very simple.

$.map(data,function(item,index){return XXX})
//使用的总结:
 //把一个数组,按照新的方式进行组装返回,和原来的数组不一样。
 //遍历data数组中的每个元素,并按照return中的计算方式 形成一个新的元素,放入返回的数组中
 var b = $.map( [55,1,2], function( item,index ) {
 return {
 "label": item,
 "value": index
 }
 });
 alert(b[0].label +" "+ b[0].value);
 //输出为 55 0
Copy after login

2. My backend is written using SpringMVC. During this period, I also encountered many problems. When performing paging processing
I used offline query, but I used execute( )In this method, the incoming session is the data of the proxy class and cannot be converted in the following method.
It caused an error. I searched on Baidu for a long time, and finally found out that it was caused by this problem.

/** * Get an executable instance of <literal>Criteria</literal>, * to actually run the query. */
 public Criteria getExecutableCriteria(Session session) {
 impl.setSession( ( SessionImplementor ) session );
 return impl;
 }
Copy after login

return (PageBean) getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
 public Object doInHibernate(Session session) throws HibernateException {
 Criteria criteria = detachedCriteria.getExecutableCriteria(session);
 ............................
 }
Copy after login

In the background, the data and format I return are slightly different from the format in BootStrap. They are different anyway

{
 "success": true,
 "message": null,
 "data": {
 "pageSize": 15,
 "rows": [
 
 {
 "userName": "333",
 "userType": 333,
 "password": "333",
 "id": 11,
 "indexcode": "333"
 },
 {
 "userName": "3",
 "userType": 333,
 "password": "333",
 "id": 5,
 "indexcode": "33333"
 }
 .......
 ],
 "total": 17,
 "totalPage": 2,
 "page": 0,
 "hasPreviousPage": true,
 "hasNextPage": true,
 "lastPage": false,
 "firstPage": false
 }
}
Copy after login

The main thing is that I use the unified return interface ActionResult here, which makes it easier to write the format. Unify the backend

**
 * Created by JetWang on 2016/10/1.
 */
public class ActionResult {
 
 private boolean success;
 
 private String message;
 
 private Object data;
 
 
 public ActionResult(){
 }
 
 public ActionResult(boolean success){
 this(success, null, null);
 }
 
 ............
 
}
Copy after login

Let’s see the effect of the front-end

Bootstrap table usage analysis

The front-end page

<%@ include file="./common/common.jsp"%> //什么公用的bootstrapt ,JQuery啊之类的引用放进去处理了
<script src="<%=baseUrl%>/libs/bootstrap-table/dist/bootstrap-table.js" type="text/javascript"></script>
<script src="<%=baseUrl%>/libs/bootstrap-table/dist/bootstrap-table-locale-all.js" type="text/javascript"> </script>
<link rel="stylesheet" href="<%=baseUrl%>/libs/bootstrap-table/dist/bootstrap-table.css" type="text/css">
//这里就是容器中放置table的
<div class="container">
 <table id="table" data-url="/cms/UserInfo/userInfoPage">//使用的路径,后台请求的URL
 </table>
</div>
Copy after login

Explanation of the more important JS code

jQuery(document).ready(function() {
 //这里你可以使用各种法师,也可以使用seajs前端模块化工具
 下面放置我们的js代码就好了
});
Copy after login

below As for the rewriting of configuration files and some events, you can check the documentation, or take a look at your source code yourself
Here you can rewrite it~~, and extentd will re-cover it!

BootstrapTable.DEFAULTS = {
 classes: &#39;table table-hover&#39;,
 locale: undefined,
 height: undefined,
 undefinedText: &#39;-&#39;,
 sortName: undefined,
 sortOrder: &#39;asc&#39;,
 sortStable: false,
 striped: false,
 columns: [[]],
 data: [],
 dataField: &#39;rows&#39;,
 method: &#39;get&#39;,
 url: undefined,
 ajax: undefined,
 cache: true,
 contentType: &#39;application/json;charset=UTF-8&#39;,//这里我就加了个utf-8
 dataType: &#39;json&#39;,
 ajaxOptions: {},
 queryParams: function (params) {//这个是设置查询时候的参数,我直接在源码中修改过,不喜欢offetset 我后台用的 是pageNo. 这样处理就比较的满足我的要求,其实也可以在后台改,麻烦!
 return params;
 },
 queryParamsType: &#39;limit&#39;, // undefined (这里是根据不同的参数,选择不同的查询的条件)
 responseHandler: function (res) {//这里我查看源码的,在ajax请求成功后,发放数据之前可以对返回的数据进行处理,返回什么部分的数据,比如我的就需要进行整改的!
 return res;
 },
 pagination: false,
 onlyInfoPagination: false,
 sidePagination: &#39;client&#39;, // client or server
 totalRows: 0, // server side need to set
 pageNumber: 1,
 pageSize: 10,
 pageList: [10, 25, 50, 100],
 paginationHAlign: &#39;right&#39;, //right, left
 paginationVAlign: &#39;bottom&#39;, //bottom, top, both
 paginationDetailHAlign: &#39;left&#39;, //right, left
 paginationPreText: &#39;‹&#39;,
 paginationNextText: &#39;›&#39;,
 search: false,
 searchOnEnterKey: false,
 strictSearch: false,
 searchAlign: &#39;right&#39;,
 selectItemName: &#39;btSelectItem&#39;,
 showHeader: true,
 showFooter: false,
 showColumns: false,
 showPaginationSwitch: false,//展示页数的选择?
 showRefresh: false,
 showToggle: false,
 buttonsAlign: &#39;right&#39;,
 smartDisplay: true,
 escape: false,
 minimumCountColumns: 1,
 idField: undefined,
 uniqueId: undefined,
 cardView: false,
 detailView: false,
 detailFormatter: function (index, row) {
 return &#39;&#39;;
 },
 trimOnSearch: true,
 clickToSelect: false,
 singleSelect: false,
 toolbar: undefined,
 toolbarAlign: &#39;left&#39;,
 checkboxHeader: true,
 sortable: true,
 silentSort: true,
 maintainSelected: false,
 searchTimeOut: 500,
 searchText: &#39;&#39;,
 iconSize: undefined,
 buttonsClass: &#39;default&#39;,
 iconsPrefix: &#39;glyphicon&#39;, // glyphicon of fa (font awesome)
 icons: {
 paginationSwitchDown: &#39;glyphicon-collapse-down icon-chevron-down&#39;,
 paginationSwitchUp: &#39;glyphicon-collapse-up icon-chevron-up&#39;,
 refresh: &#39;glyphicon-refresh icon-refresh&#39;,
 toggle: &#39;glyphicon-list-alt icon-list-alt&#39;,
 columns: &#39;glyphicon-th icon-th&#39;,
 detailOpen: &#39;glyphicon-plus icon-plus&#39;,
 detailClose: &#39;glyphicon-minus icon-minus&#39;
 },
 
 customSearch: $.noop,
 
 customSort: $.noop,
 
 rowStyle: function (row, index) {
 return {};
 },
 
 rowAttributes: function (row, index) {
 return {};
 },
 
 footerStyle: function (row, index) {
 return {};
 },
 
 onAll: function (name, args) {
 return false;
 },
 onClickCell: function (field, value, row, $element) {
 return false;
 },
 onDblClickCell: function (field, value, row, $element) {
 return false;
 },
 onClickRow: function (item, $element) {
 return false;
 },
 onDblClickRow: function (item, $element) {
 return false;
 },
 onSort: function (name, order) {
 return false;
 },
 onCheck: function (row) {
 return false;
 },
 onUncheck: function (row) {
 return false;
 },
 onCheckAll: function (rows) {
 return false;
 },
 onUncheckAll: function (rows) {
 return false;
 },
 onCheckSome: function (rows) {
 return false;
 },
 onUncheckSome: function (rows) {
 return false;
 },
 onLoadSuccess: function (data) {
 return false;
 },
 onLoadError: function (status) {
 return false;
 },
 onColumnSwitch: function (field, checked) {
 return false;
 },
 onPageChange: function (number, size) {
 return false;
 },
 onSearch: function (text) {
 return false;
 },
 onToggle: function (cardView) {
 return false;
 },
 onPreBody: function (data) {
 return false;
 },
 onPostBody: function () {
 return false;
 },
 onPostHeader: function () {
 return false;
 },
 onExpandRow: function (index, row, $detail) {
 return false;
 },
 onCollapseRow: function (index, row) {
 return false;
 },
 onRefreshOptions: function (options) {
 return false;
 },
 onRefresh: function (params) {
 return false;
 },
 onResetView: function () {
 return false;
 }
 };
Copy after login

Looking at the above, I basically know how to go and write! In fact, I didn’t dare to play like this before, but my instructor taught me how to play during my previous internship, so I dared. I believe that I can play these things well!

function initTable() {
$table.bootstrapTable({
striped: true, //表格显示条纹
pagination: true, //启动分页
pageSize: 15, //每页显示的记录数
pageNumber:1, //当前第几页
pageList: [10, 15, 20, 25], //记录数可选列表
search: false, //是否启用查询
showColumns: true, //显示下拉框勾选要显示的列
showRefresh: true, //显示刷新按钮
sidePagination: "server", //表示服务端请求
//设置为undefined可以获取pageNumber,pageSize,searchText,sortName,sortOrder
//设置为limit可以获取limit, offset, search, sort, order
responseHandler:function(res){
//远程数据加载之前,处理程序响应数据格式,对象包含的参数: 我们可以对返回的数据格式进行处理
//在ajax后我们可以在这里进行一些事件的处理
return res.data;
},
queryParamsType : "undefined",
queryParams: function queryParams(params) { //设置查询参数
var param = {
//这里是在ajax发送请求的时候设置一些参数 params有什么东西,自己看看源码就知道了
pageNo: params.pageNumber,
pageSize: params.pageSize
};
return param;
},
onLoadSuccess: function(data){ //加载成功时执行
alert("加载成功"+data);
},
onLoadError: function(){ //加载失败时执行
layer.msg("加载数据失败", {time : 1500, icon : 2});
},
height: getHeight(),
columns: [
{
field: &#39;state&#39;,
checkbox: true,
align: &#39;center&#39;,
valign: &#39;middle&#39;
}, {
title: &#39;ID&#39;,
field: &#39;id&#39;,
align: &#39;center&#39;,
valign: &#39;middle&#39;
},
{
field: &#39;userName&#39;,
title: &#39;UserName&#39;,
sortable: true,
footerFormatter: totalNameFormatter,
align: &#39;center&#39;
}, {
field: &#39;userType&#39;,
title: &#39;UserType&#39;,
sortable: true,
align: &#39;center&#39;
},
{
field: &#39;password&#39;,
title: &#39;UserPass&#39;,
sortable: true,
align: &#39;center&#39;
},{
field: &#39;indexcode&#39;,
title: &#39;Indexcode&#39;,
sortable: true,
align: &#39;center&#39;
},{
field: &#39;operate&#39;,
title: &#39;Item Operate&#39;,
align: &#39;center&#39;,
events: operateEvents,
formatter: operateFormatter
}
]
});
Copy after login

The above footerFormatter and formatter are events that process the display of the current column. The document is as follows
formatter:
The context (this) is the column Object. The cell formatter function, take three parameters: value: the field value. row: the row record data. index: the row index.
footerFormatter :
The context (this) is the column Object. The function, take one parameter:
data: Array of all the data rows. the function should return a string with the text to show in the footer cell.
All are processed and displayed for the current column

The following is to add two buttons in a cell

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

It can also be found here Just add event processing

<%--{
  title: &#39;操作&#39;,
  field: &#39;id&#39;,
  align: &#39;center&#39;,
  formatter:function(value,row,index){
  var e = &#39;<a href="#" rel="nofollow" target="_blank" mce_href="#" rel="nofollow" target="_blank" onclick="edit(\&#39;&#39;+ row.id + &#39;\&#39;)">编辑</a> &#39;;
  var d = &#39;<a href="#" rel="nofollow" target="_blank" mce_href="#" rel="nofollow" target="_blank" onclick="del(\&#39;&#39;+ row.id +&#39;\&#39;)">删除</a> &#39;;
  return e+d;
  也可以这样处理事件的
 }
 }--%>
Copy after login

The official document says that processing events can be handled as follows

The cell events listener when you use formatter function, take four parameters: event: the jQuery event. value: the field value. row: the row record data. index: the row index.

Example code:

{
field: 'operate',
title: 'Item Operate',
align: 'center',
events: operateEvents,
formatter: operateFormatter
}
function operateFormatter(value, row, index) {
return [ &#39;<a class="like" href="javascript:void(0)" title="Like">&#39;, &#39;<i class="glyphicon glyphicon-heart"></i>&#39;, &#39;</a> &#39;, &#39;<a class="remove" href="javascript:void(0)" title="Remove">&#39;, &#39;<i class="glyphicon glyphicon-remove"></i>&#39;, &#39;</a>&#39; ].join(&#39;&#39;);
}
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]
});
}
};
Copy after login

handles the processing of events existing in the system. The document says

$(&#39;#table&#39;).bootstrapTable({
 onEventName: function (arg1, arg2, ...) {
 // ...
 }
});
 
$(&#39;#table&#39;).on(&#39;event-name.bs.table&#39;, function (e, arg1, arg2, ...) {
 // ...
});
//这个名字文档中很多!
onAll all.bs.table
  name, args
  Fires when all events trigger, the parameters contain:
  name: the event name,
  args: the event data.
Copy after login

handles some Methods, such as how many rows are currently selected, select all, etc.

//The calling method syntax: $(&#39;#table&#39;).bootstrapTable(&#39;method&#39;, parameter);
 
//1 当前选择选的框框的id
getSelections none Return selected rows, when no record selected, an empty array will return.
 
//2.全选
getAllSelections none Return all selected rows contain search or filter, when no record selected, an empty array will return.
 $table.on(&#39;all.bs.table&#39;, function (e, name, args) {
 console.log(name, args);
 });
//3.删除 前台的数据,不需要从后台重新加载
remove params Remove data from table, the params contains two properties:
field: the field name of remove rows.
values: the array of values for rows which should be removed.
Copy after login

....many, many things!
A delete button to delete all selected events! Isn’t it great!

function getIdSelections() {
return $.map($table.bootstrapTable(&#39;getSelections&#39;), function (row) {
return row.id
});
}
$remove.click(function () {
var ids = getIdSelections();
$table.bootstrapTable(&#39;remove&#39;, {
field: &#39;id&#39;,
values: ids
});
$remove.prop(&#39;disabled&#39;, true);
});
Copy after login


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 Recommendations
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!