bootstrap中使用datatables

今天大象研究了下datatables表格,下面来介绍下datatables,我是在bootstrap中使用的,引入必须的JS后就可以开始使用了,首先表格的HTML

<div class="row-fluid">
      <div class="span12">
        <div class="box corner-all">
          <div class="box-header grd-white corner-top">
            <div class="header-control"> <a data-toggle="modal" data-target="#myModal2"><i class="icon-external-link"></i></a> <a data-box="collapse"><i class="icofont-caret-up"></i></a> <a data-box="close" data-hide="bounceOutRight">&times;</a> </div>
            <span>用户列表</span> </div>
          <div class="box-body">
            <table id="datatables" class="table table-bordered table-striped responsive">
              <thead>
                <tr>
                  <th>Id</th>
                  <th>规则名</th>
                  <th>中文名</th>
                  <th>状态</th>
                  <th style="width:290px;">操作</th>
                </tr>
              </thead>
              <tbody>
              </tbody>
            </table>
          </div>
          <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"                                          aria-hidden="true" style="display:none;">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal" aria-hidden="false">&times;</button>
                  <h4 class="modal-title" id="myModalLabel">规则编辑</h4>
                </div>
                <div class="modal-body">
                  <form class="form-horizontal">
                    <div class="control-group">
                      <label class="control-label" for="Name">规则标识</label>
                      <div class="controls">
                        <input type="text" id="Name" name="Name">
                        (英文小写)
                        <input type="hidden" name="Id" id="Id" >
                      </div>
                    </div>
                    <div class="control-group">
                      <label class="control-label" for="Title">规则中文名称</label>
                      <div class="controls">
                        <input type="text" id="Title" name="Title">
                      </div>
                    </div>
                    <div class="control-group">
                      <label class="control-label" for="Condition">规则表达式</label>
                      <div class="controls">
                        <textarea id="Condition" name="Condition"></textarea>
                      </div>
                    </div>
                    <div class="control-group">
                      <div class="controls">
                        <label class="checkbox">
                          <input name="Status" type="checkbox" id="Status" value="1">
                          激活 </label>
                      </div>
                    </div>
                  </form>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                  <button type="button" class="btn btn-primary">保存</button>
                </div>
              </div>
              <!-- /.modal-content --> 
            </div>
            <!-- /.modal-dialog --> 
          </div>
          
          <!-- /box-body --> 
        </div>
        <!-- /box --> 
      </div>
      <!-- /span --> 
    </div>




datatables增删改查的实现

<script type="text/javascript">
$(function(){
	var id = 0;//修改数据的ID
	var table = $('#datatables');//表格对象
		
	//获取修改时显示的数据,弹出modal模态对话框
	$(document).delegate(".btn.btn-success","click",function(){
		$("#myModal #myModalLabel").text("修改权限规则");
		id = $(this).attr("data-title");
		data={id:id}
		$.ajax({
			type:"GET",
			data:data,
			url:"/rule/edit",
			dataType:"json",
			success: function(json){
				if(json.status){
					$("#myModal #Id").val(json.data.Id);							
					$("#myModal #Name").val(json.data.Name);
					$("#myModal #Title").val(json.data.Title);
					$("#myModal #Condition").val(json.data.Condition);
					if(json.data.Status==1){$("#myModal #Status").attr("checked","checked");
					}else{$("#myModal #Status").attr("checked",false);}													
				}else{
					alert(json.msg);
				}
					
			}	
		});					
		$('#myModal').modal({keyboard:false,show:true})
	})
				
				
	//保存,增加和修改时都使用这个方法提交表单,区别在于修改时有ID参数而增加时没有
	$(document).delegate(".modal-dialog .btn.btn-primary","click",function(){
		data = $(".form-horizontal").serialize();
		$.ajax({
			type:"POST",
			data:data,
			url:"/rule/save",
			dataType:"json",
			success: function(json){
				alert(json.msg);
				if(json.status==1){
				   $('#myModal').modal("hide");								  
				   table.fnClearTable();//清空数据表
				}
				
			}	
		});
	});
	  
	//增加,弹出modal模态对话框
	$("#account_add").click(function(){
		$("#myModal #myModalLabel").text("增加权限规则");
		$("#myModal #id").val("");
		$("#myModal #name").val("");
		$("#myModal #title").val("");
		$("#myModal #condition").val("");
		$("#myModal #status").attr("checked","checked");
		$('#myModal').modal({keyboard:false,show:true})
	});
			
	//datatables显示列表
	table.dataTable( {
	  "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",//定义DataTable布局的一个强大属性
	  "sPaginationType": "bootstrap",//分页样式使用bootstrap
	  "oLanguage": {//语言设置
			  "sLengthMenu": "每页显示  _MENU_ 条记录",  
			  "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
			  "oPaginate": {
				  "sFirst": "首页",
				  "sPrevious": "前一页",
				  "sNext": "后一页",
				  "sLast": "尾页"
				  },
			  "sZeroRecords": "抱歉, 没有找到",
			  "sInfoEmpty": "没有数据"
			},
	 "bProcessing": true, //当datatable获取数据时候是否显示正在处理提示信息。
	 "bServerSide": true, //客户端处理分页
	 "sAjaxSource": "/rule/list", //ajax请求地址
	 'bStateSave': true, //开关,是否打开客户端状态记录功能。这个数据是记录在cookies中的,打开了这个记录后,即使刷新一次页面,或重新打开浏览器,之前的状态都是保存下来的
	 "aoColumnDefs": [{ //给每个单独的列设置不同的填充,或者使用aoColumns也行
					  "aTargets": [3],
					  "mData": null,
					  "bSortable": false,
					  "bSearchable": false,
					  "mRender": function (data, type, full) {
						  if(full[3] == 1){
							 return "使用中"  
						  }else if(full[3] == 0){
							 return "禁用" 
						  }
					  }
				  },{
					  "aTargets": [4],
					  "mData": null,
					  "bSortable": false,
					  "bSearchable": false,
					  "mRender": function (data, type, full) {
						  return '<a data-toggle="modal" data-target="#myModal"  data-title="' + full[0] + '"  class="btn btn-success" href="#"><i class="icon-edit icon-white"></i>修改</a>' +'&nbsp;&nbsp;'+'<a   data-title="' + full[0] + '"  class="btn btn-primary" href="/config/edit?aid=' + full[0] + '"><i class="icon-wrench icon-white" ></i>配置</a>' +'&nbsp;&nbsp;'+'<a   alt="' + full[2] + '"  class="btn btn-info" href="#"  data-toggle="modal" data-target="#daima"><i class="icon-tasks icon-white"></i>代码</a>' +'&nbsp;&nbsp;'+'<a   data-title="' + full[0] + '"  class="btn btn-warning" href="/service/show?aid=' + full[0] + '"><i class="icon-user icon-white"></i>客服</a>';
					  }
				  }]
	
	}); 	
});
</script>




服务端返回数据为JSON格式的,需要你返回的是这样的JSON格式,我使用了GO来返回这些数据,你也可以使用PHP或者其它程序返回

{
  "aaData": [
    [
      1,
      "基本面夺555",
      "什么呀5566",
      1
    ],
    [
      2,
      "rule_show",
      "权限规则显示",
      1
    ],
    [
      3,
      "rule_save",
      "权限规则编辑",
      1
    ],
    [
      4,
      "rule_del",
      "权限规则删除",
      1
    ],
    [
      5,
      "account/show",
      "帐户显示权限",
      1
    ],
    [
      6,
      "account/edit",
      "帐户修改权限",
      1
    ],
    [
      7,
      "account/save",
      "帐户编辑权限",
      1
    ]
  ],
  "iTotalDisplayRecords": 7,
  "iTotalRecords": 7,
  "sEcho": "1"
}

golang处理部分

/*
* 显示datatables列表页数据
 */
func (this *RuleController) List() {
	var rule models.Rule

	aColumns := []string{
		"Id",
		"Name",
		"Title",
		"Status",
	}
	
	maps, count, counts := d.Datatables(aColumns, rule, this.Ctx.Input)

	var output = make([][]interface{}, len(maps))
	for i, m := range maps {
		for _, v := range aColumns {
			output[i] = append(output[i], m[v])
		}
	}

	data := make(map[string]interface{}, count)
	data["sEcho"] = this.GetString("sEcho")
	data["iTotalRecords"] = counts
	data["iTotalDisplayRecords"] = count
	data["aaData"] = output

	this.Data["json"] = data
	this.ServeJson()

}



golang具体处理过程

/*
 * aColumns []string `SQL Columns to display`
 * thismodel interface{} `SQL model to use`
 * ctx *context.Context `Beego ctx which contains httpcontext`
 * maps []orm.Params `return result in a interface map as []orm.Params`
 * count int64 `return iTotalDisplayRecords`
 * counts int64 `return iTotalRecords`
 *
 */
func Datatables(aColumns []string, thismodel interface{}, Input *context.BeegoInput) (maps []orm.Params, count int64, counts int64) {
	/*
	 * Paging
	 * 分页请求
	 */
	iDisplayStart, _ := strconv.Atoi(Input.Query("iDisplayStart"))
	iDisplayLength, _ := strconv.Atoi(Input.Query("iDisplayLength"))
	/*
	 * Ordering
	 * 排序请求
	 */
	querysOrder := []string{}
	if iSortCol_0, _ := strconv.Atoi(Input.Query("iSortCol_0")); iSortCol_0 > -1 {
		ranges, _ := strconv.Atoi(Input.Query("iSortingCols"))
		for i := 0; i < ranges; i++ {
			istring := strconv.Itoa(i)
			if iSortcol := Input.Query("bSortable_" + Input.Query("iSortCol_"+istring)); iSortcol == "true" {
				sordir := Input.Query("sSortDir_" + istring)
				thisSortCol, _ := strconv.Atoi(Input.Query("iSortCol_" + istring))
				if sordir == "asc" {
					querysOrder = append(querysOrder, aColumns[thisSortCol])
				} else {
					querysOrder = append(querysOrder, "-"+aColumns[thisSortCol])
				}
			}
		}
	}
	/*
	 * Filtering
	 * 快速过滤器
	 */
	//querysFilter := []string{}
	cond := orm.NewCondition()
	if len(Input.Query("sSearch")) > 0 {
		for i := 0; i < len(aColumns); i++ {
			cond = cond.Or(aColumns[i]+"__icontains", Input.Query("sSearch"))
		}

	}
	/* Individual column filtering */
	for i := 0; i < len(aColumns); i++ {
		if Input.Query("bSearchable_"+strconv.Itoa(i)) == "true" && len(Input.Query("sSearch_"+strconv.Itoa(i))) > 0 {
			cond = cond.And(aColumns[i]+"__icontains", Input.Query("sSearch"))
		}
	}
	/*
	 * GetData
	 * 数据请求
	 */
	o := orm.NewOrm()
	qs := o.QueryTable(thismodel)
	counts, _ = qs.Count()
	qs = qs.Limit(iDisplayLength, iDisplayStart)
	qs = qs.SetCond(cond)
	for _, v := range querysOrder {
		qs = qs.OrderBy(v)
	}
	qs.Values(&maps)
	count, _ = qs.Count()
	return maps, count, counts
}



转载于:https://my.oschina.net/tongjh/blog/213932

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值