bootstrap 插件table

效果图:

功能: 1、动态搜索功能。

          2、根据字段,进行排序。

          3、可以进行sql、csv等的导出

          4、刷新功能

          5、显示所有数据条目。

后端代码:

  1 from django.shortcuts import render ,HttpResponse
  2 from table.models import *
  3 from django.db.models import Q
  4 # Create your views here.
  5 def data_query(request):
  6     import json
  7     list_1 = []
  8     list_info = {}
  9     d={}
 10     query_sort=request.GET.get('sort',None)#排序的字段。
 11     incre_add=request.GET.get('order',None)#正向还是反向排序。
 12     offset=request.GET.get('offset',None)#请求第几条数据开始。
 13     limit=request.GET.get('limit',None)#每页的数据条数。
 14     search_request=request.GET.get('search',None)#获取搜索的字段。
 15     obj = host.objects.all()
 16     total = obj.count()
 17     if query_sort and limit!=None and offset!=None and not search_request:# order  by query_sort asc
 18         end = int(offset) + int(limit)
 19         start = int(offset)
 20         if incre_add=='asc':
 21             sort_obj=host.objects.order_by(str(query_sort))
 22             sort_obj = sort_obj[start:end]
 23             sort_total=len(sort_obj)
 24             for i in sort_obj:
 25                 d['name'] = i.name
 26                 d['IP'] = i.IP
 27                 d['status'] = i.status
 28                 d['id'] = i.id
 29                 list_1.append(d)
 30                 d={}
 31             list_info['total'] = total
 32             list_info['rows'] = list_1
 33             return HttpResponse(json.dumps(list_info))
 34 
 35         else:#order by desc
 36             sort_obj = host.objects.order_by('-'+str(query_sort))
 37             sort_obj = sort_obj[start:end]
 38             for i in sort_obj:
 39                 d['name'] = i.name
 40                 d['IP'] = i.IP
 41                 d['status'] = i.status
 42                 d['id'] = i.id
 43                 list_1.append(d)
 44                 d = {}
 45             list_info['total'] = total
 46             list_info['rows'] = list_1
 47             return HttpResponse(json.dumps(list_info))
 48     elif query_sort and  not limit and not  offset:
 49         if incre_add == 'asc':
 50             sort_obj = host.objects.order_by(str(query_sort))
 51             for i in sort_obj:
 52                 d['name'] = i.name
 53                 d['IP'] = i.IP
 54                 d['status'] = i.status
 55                 d['id'] = i.id
 56                 list_1.append(d)
 57                 print(d)
 58                 d = {}
 59             list_info['total'] = total
 60             list_info['rows'] = list_1
 61             return HttpResponse(json.dumps(list_info))
 62         else:
 63             sort_obj = host.objects.order_by('-' + str(query_sort))
 64             for i in sort_obj:
 65                 d['name'] = i.name
 66                 d['IP'] = i.IP
 67                 d['status'] = i.status
 68                 d['id'] = i.id
 69                 list_1.append(d)
 70             list_info['total'] = total
 71             list_info['rows'] = list_1
 72             return HttpResponse(json.dumps(list_info))
 73     if search_request:#search what  user enter
 74         search_obj=host.objects.filter(Q(IP__contains="%s"%(search_request))|
 75                                        Q(status__icontains="%s"%(search_request))|
 76                                        Q(name__icontains="%s"%(search_request)))
 77         if search_obj:
 78             total_sear = search_obj.count()
 79             d = {}
 80             if total_sear > int(limit):
 81                 end = int(offset) + int(limit)
 82                 start = int(offset)
 83                 search_obj=search_obj[start:end]
 84             for i in search_obj:
 85                 d['name'] = i.name
 86                 d['IP'] = i.IP
 87                 d['status'] = i.status
 88                 d['id'] = i.id
 89                 list_1.append(d)
 90                 d = {}
 91             list_info['total'] = total_sear
 92             list_info['rows'] = list_1
 93             return HttpResponse(json.dumps(list_info))
 94         else:
 95             total_sear=0
 96             list_info['total'] = total_sear
 97             list_info['rows'] ={}
 98             return HttpResponse(json.dumps(list_info))
 99     if incre_add and offset==None and limit==None and query_sort==None:#clck pagefoot and query db.
100         list_1=[]
101         d = {}
102         for i in obj:
103             d['name'] = i.name
104             d['IP'] = i.IP
105             d['status'] = i.status
106             d['id'] = i.id
107             list_1.append(d)
108         import json
109         list_info['total'] = total
110         list_info['rows'] = list_1
111         return HttpResponse(json.dumps(list_info))
112     try:
113         end=int(offset)+int(limit)
114         start=int(offset)
115     except Exception:
116         return render(request,'table.html')
117     else:
118         list_1=[]
119         obj = obj[start:end]
120         d = {}
121         for i in obj:
122             d['name'] = i.name
123             d['IP'] = i.IP
124             d['status'] = i.status
125             d['id'] = i.id
126             list_1.append(d)
127             d = {}
128         import json
129         list_info['total'] = total
130         list_info['rows'] = list_1
131         return HttpResponse(json.dumps(list_info))
132 

 

前端代码:

  1 <!DOCTYPE html>
  2 <html>
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Bootstrap Table Examples</title>
  6     <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
  7     <link rel="stylesheet" href="/static/bootstrap-table/font-awesome/css/font-awesome.css">
  8     <link rel="stylesheet" href="/static/bootstrap-table/bootstrap-table.css">
  9     <link rel="stylesheet" href="//rawgit.com/vitalets/x-editable/master/dist/bootstrap3-editable/css/bootstrap-editable.css">
 10     <link rel="stylesheet" href="/static/css/examples.css">
 11     <script src="/static/js/jquery-2.1.1.min.js"></script>
 12     <script src="/static/js/bootstrap.min.js"></script>
 13     <script src="/static/js/ga.js"></script>
 14     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
 15     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
 16     <!--[if lt IE 9]>
 17     <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script>
 18     <script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
 19     <script src="//cdnjs.cloudflare.com/ajax/libs/json2/20140204/json2.min.js"></script>
 20     <![endif]-->
 21     <style>
 22         .fixed-table-body{
 23             height: auto;
 24         }
 25     </style>
 26 </head>
 27 <body>
 28 <div class="container">
 29     <h2>故障模拟 </h2>
 30     <div id="toolbar">
 31 {#        <button id="remove" class="btn btn-danger" disabled>#}
 32 {#            <i class="glyphicon glyphicon-remove"></i> Delete#}
 33 {#        </button>#}
 34 
 35     </div>
 36     <table id="table"
 37            data-toolbar="#toolbar"
 38            data-search="true"
 39            data-page-size="14"
 40            data-show-refresh="true"
 41            data-show-toggle="true"
 42            data-show-columns="true"
 43            data-show-export="true"
 44            data-minimum-count-columns="2"
 45            data-show-pagination-switch="true"
 46            data-pagination="true"
 47            data-id-field="id"
 48            data-page-list="[14, 28, 56, ALL]"
 49            data-show-footer="false"
 50            data-side-pagination="server"
 51            data-url="/table/"
 52            data-response-handler="responseHandler">
 53     </table>
 54 </div>
 55 
 56 <script>
 57     var $table = $('#table'),
 58         $remove = $('#remove'),
 59         selections = [];
 60 
 61     function initTable() {
 62         $table.bootstrapTable({
 63             height: getHeight(),
 64             columns: [
 65                 [
 66                     {
 67                         field: 'state',
 68                         checkbox: true,
 69                         align: 'center',
 70                         valign: 'middle'
 71                     },
 72                     {
 73                         field: 'id',
 74                         title: 'Server ID',
 75                         sortable: true,
 76                         footerFormatter: totalNameFormatter,
 77                         align: 'center'
 78                     },
 79                     {
 80                         field: 'IP',
 81                         title: 'IP',
 82                         sortable: true,
 83                         footerFormatter: totalNameFormatter,
 84                         align: 'center'
 85                     }, {
 86                         field: 'status',
 87                         title: 'status ',
 88                         sortable: true,
 89                         align: 'center',
 90                         footerFormatter: totalPriceFormatter
 91                     }, {
 92                         field: 'name',
 93                         title: 'name ',
 94                         sortable: true,
 95                         align: 'center',
 96                         footerFormatter: totalPriceFormatter
 97                     }
 98                 ]
 99             ]
100         });
101         // sometimes footer render error.
102         setTimeout(function () {
103             $table.bootstrapTable('resetView');
104         }, 200);
105         $table.on('check.bs.table uncheck.bs.table ' +
106                 'check-all.bs.table uncheck-all.bs.table', function () {
107             $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);
108 
109             // save your data, here just save the current page
110             selections = getIdSelections();
111             // push or splice the selections if you want to save all data selections
112         });
113         $table.on('expand-row.bs.table', function (e, index, row, $detail) {
114             if (index % 2 == 1) {
115                 $detail.html('Loading from ajax request...');
116                 $.get('LICENSE', function (res) {
117                     $detail.html(res.replace(/\n/g, '<br>'));
118                 });
119             }
120         });
121         $table.on('all.bs.table', function (e, name, args) {
122             console.log(name, args);
123         });
124         $remove.click(function () {
125             var ids = getIdSelections();
126             $table.bootstrapTable('remove', {
127                 field: 'id',
128                 values: ids
129             });
130             $remove.prop('disabled', true);
131         });
132         $(window).resize(function () {
133             $table.bootstrapTable('resetView', {
134                 height: getHeight()
135             });
136         });
137     }
138 
139     function getIdSelections() {
140         return $.map($table.bootstrapTable('getSelections'), function (row) {
141             return row.id
142         });
143     }
144 
145     function responseHandler(res) {
146         $.each(res.rows, function (i, row) {
147             row.state = $.inArray(row.id, selections) !== -1;
148         });
149         return res;
150     }
151 
152     function detailFormatter(index, row) {
153         var html = [];
154         $.each(row, function (key, value) {
155             html.push('<p><b>' + key + ':</b> ' + value + '</p>');
156         });
157         return html.join('');
158     }
159 
160     function operateFormatter(value, row, index) {
161         return [
162             '<a class="like" href="javascript:void(0)" title="Like">',
163             '<i class="glyphicon glyphicon-heart"></i>',
164             '</a>  ',
165             '<a class="remove" href="javascript:void(0)" title="Remove">',
166             '<i class="glyphicon glyphicon-remove"></i>',
167             '</a>'
168         ].join('');
169     }
170 
171     window.operateEvents = {
172         'click .like': function (e, value, row, index) {
173             alert('You click like action, row: ' + JSON.stringify(row));
174         },
175         'click .remove': function (e, value, row, index) {
176             $table.bootstrapTable('remove', {
177                 field: 'id',
178                 values: [row.id]
179             });
180         }
181     };
182 
183     function totalTextFormatter(data) {
184         return 'Total';
185     }
186 
187     function totalNameFormatter(data) {
188         return data.length;
189     }
190 
191     function totalPriceFormatter(data) {
192         var total = 0;
193         $.each(data, function (i, row) {
194             total += +(row.price.substring(1));
195         });
196         return '$' + total;
197     }
198 
199     function getHeight() {
200         return $(window).height() - $('h1').outerHeight(true);
201     }
202 
203     $(function () {
204         var scripts = [
205                 location.search.substring(1) || '/static/js/bootstrap-table.js',
206                 '/static/js/bootstrap-table-export.js',
207                 '/static/js/tableExport.js',
208                 '/static/js/bootstrap-table-editable.js',
209                 '/static/js/bootstrap-editable.js'
210             ],
211             eachSeries = function (arr, iterator, callback) {
212                 callback = callback || function () {};
213                 if (!arr.length) {
214                     return callback();
215                 }
216                 var completed = 0;
217                 var iterate = function () {
218                     iterator(arr[completed], function (err) {
219                         if (err) {
220                             callback(err);
221                             callback = function () {};
222                         }
223                         else {
224                             completed += 1;
225                             if (completed >= arr.length) {
226                                 callback(null);
227                             }
228                             else {
229                                 iterate();
230                             }
231                         }
232                     });
233                 };
234                 iterate();
235             };
236 
237         eachSeries(scripts, getScript, initTable);
238     });
239 
240     function getScript(url, callback) {
241         var head = document.getElementsByTagName('head')[0];
242         var script = document.createElement('script');
243         script.src = url;
244 
245         var done = false;
246         // Attach handlers for all browsers
247         script.onload = script.onreadystatechange = function() {
248             if (!done && (!this.readyState ||
249                     this.readyState == 'loaded' || this.readyState == 'complete')) {
250                 done = true;
251                 if (callback)
252                     callback();
253 
254                 // Handle memory leak in IE
255                 script.onload = script.onreadystatechange = null;
256             }
257         };
258 
259         head.appendChild(script);
260 
261         // We handle everything using the script element injection
262         return undefined;
263     }
264 </script>
265 </body>
266 </html>

 

posted @ 2017-05-25 14:10  evil_liu  阅读(190)  评论(0)    收藏  举报