欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在Laravel中使用DataTables插件的方法

程序员文章站 2022-10-06 20:40:59
datatables 是一个 jquery 的表格插件,记录一下在 laravel 中使用的常用功能和用法,比如 ajax 获取数据,自定义搜索,效果展现,选项说明等等,有...

datatables 是一个 jquery 的表格插件,记录一下在 laravel 中使用的常用功能和用法,比如 ajax 获取数据,自定义搜索,效果展现,选项说明等等,有一些细节记录下来方便以后查看。

laravel 控制器方法

接受 ajax get 请求,返回数据。

datatables 会自带一些参数过来,需要按照格式返回数据,比如分页等。见 datatables 官方文档说明。

代码如下:

// ajax get 获取列表数据
public function getlist(request $request)
{
  $dynamictype = $request->get('dynamic_type');
  $draw = $request->get('draw');
  $start = $request->get('start');
  $length = $request->get('length');
  $groupid = $request->get('group_id');
  $dynamicid = $request->get('dynamic_id');
  $userid = $request->get('userid');
  $isaudit = $request->get('is_audit', 0);

  if (!$dynamictype || !in_array($dynamictype, [1, 2])) {
    return response()->json(['error' => '缺少参数!']);
  }

  $builder = dynamics::select(['id', 'userid', 'group_id', 'dynamic_id', 'dynamic_type', 'content', 'money', 'is_audit', 'audited_at'])->where('dynamic_type', $dynamictype);

  //自定义搜索
  if ($groupid) {
    $builder->where('group_id', $groupid);
  }

  if ($dynamicid) {
    $builder->where('dynamic_id', $dynamicid);
  }

  if ($userid) {
    $builder->where('userid', $userid);
  }

  if (!is_null($isaudit)) {
    $builder->where('is_audit', $isaudit);
  }

  $total = $builder->count();
  $list = $builder->orderby('id', 'desc')->offset($start)->take($length)->get()->toarray();


  $imginfo = [];
  $dynamicids = $this->getdynamicids($list);
  if ($dynamicids) {
    $imginfo = dynamicimage::wherein('dynamic_id', $dynamicids)->pluck('images', 'dynamic_id');
  }

  $fillimages = function ($item) use ($imginfo) {
    if (isset($imginfo[$item['dynamic_id']])) {
      $item["images"] = json_decode($imginfo[$item['dynamic_id']]);
    } else {
      $item["images"] = [];
    }
    return $item;
  };
  $list = array_map($fillimages, $list);

  $data = [];
  $data["draw"] = $draw;
  $data["recordstotal"] = $total;
  $data["recordsfiltered"] = $total;
  $data["data"] = $list;
  return response()->json($data);
}


// ajax get 获取列表数据
public function getlist(request $request)
{
  $dynamictype = $request->get('dynamic_type');
  $draw = $request->get('draw');
  $start = $request->get('start');
  $length = $request->get('length');
  $groupid = $request->get('group_id');
  $dynamicid = $request->get('dynamic_id');
  $userid = $request->get('userid');
  $isaudit = $request->get('is_audit', 0);
 
  if (!$dynamictype || !in_array($dynamictype, [1, 2])) {
    return response()->json(['error' => '缺少参数!']);
  }
 
  $builder = dynamics::select(['id', 'userid', 'group_id', 'dynamic_id', 'dynamic_type', 'content', 'money', 'is_audit', 'audited_at'])->where('dynamic_type', $dynamictype);
 
  //自定义搜索
  if ($groupid) {
    $builder->where('group_id', $groupid);
  }
 
  if ($dynamicid) {
    $builder->where('dynamic_id', $dynamicid);
  }
 
  if ($userid) {
    $builder->where('userid', $userid);
  }
 
  if (!is_null($isaudit)) {
    $builder->where('is_audit', $isaudit);
  }
 
  $total = $builder->count();
  $list = $builder->orderby('id', 'desc')->offset($start)->take($length)->get()->toarray();
 
 
  $imginfo = [];
  $dynamicids = $this->getdynamicids($list);
  if ($dynamicids) {
    $imginfo = dynamicimage::wherein('dynamic_id', $dynamicids)->pluck('images', 'dynamic_id');
  }
 
  $fillimages = function ($item) use ($imginfo) {
    if (isset($imginfo[$item['dynamic_id']])) {
      $item["images"] = json_decode($imginfo[$item['dynamic_id']]);
    } else {
      $item["images"] = [];
    }
    return $item;
  };
  $list = array_map($fillimages, $list);
 
  $data = [];
  $data["draw"] = $draw;
  $data["recordstotal"] = $total;
  $data["recordsfiltered"] = $total;
  $data["data"] = $list;
  return response()->json($data);
}

datatables 发 ajax 请求及一些选项设置

columndefs 用来自定义每个字段如何展现,可以封装自己的展现逻辑,也可以获取到这一行各个字段的值。

createdrow 可以改变创建每一行的行为,比如修改这一行的样式等等。

table.draw() 方法可以重新发起 ajax 请求。

<script type="text/javascript">
  $datatable = $("#datatable");
  var table = $datatable.datatable({
    "processing": true,
    "serverside": true,
    "pagelength": 25,
    "lengthmenu": [10, 25, 50, 75, 100, 200],
    "ajax": {
      "url": "{{ route('audit.getlist') }}",
      "data": function (data) {
        data.dynamic_type = "{{ request::get('dynamic_type', 1) }}";
        data.group_id = $("#group_id").val();
        data.dynamic_id = $("#dynamic_id").val();
        data.userid = $("#userid").val();
        data.is_audit = $("#is_audit").val();
        data.t = "{{ time() }}";
      }
    },
    "columns": [
      {"data": "id"},
      {"data": "userid"},
      {"data": "group_id"},
      {"data": "dynamic_type"},
      {"data": "dynamic_id"},
      {"data": "content"},
      {"data": "images"},
      {"data": "money"},
      {"data": "is_audit"},
      {"data": "audited_at"}
    ],
    "columndefs": [
      {
        "render": function (data, type, row) {
          if (data == 1) {
            return "活动";
          } else if (data == 2) {
            return "动态";
          }
        },
        "targets": 3
      },
      {
        "render": function (data, type, row) {
          html = "";
          $.each(data, function (k, v) {
            html += "<a href='" + v.origin + "' target='_blank'><img src='" + v.origin + "' width='160' style='margin-bottom: 2px;'>";
          });
          return html;
        },
        "targets": 6
      },
      {
        "render": function (data, type, row) {
          if (data == 0) {
            return "未审核";
          } else if (data == 1) {
            return "审核通过";
          } else if (data == -1) {
            return "审核不通过";
          }
        },
        "targets": 8
      },
      {
        "render": function (data, type, row) {
          if (row.is_audit == 0) {
            return "<a class='btn btn-primary audit' data-type = 1>通过</a> <a class='btn btn-danger audit' data-type = 2>不通过</a>";
          }
          return "-";
        },
        "targets": 10
      }
    ],
    "createdrow": function (row, data, index) {
      $('td', row).eq(4).attr('style', 'word-break:break-all');
      $('td', row).eq(2).attr('style', 'word-break:break-all');
      $('td', row).eq(5).attr('style', 'word-break:break-all');
    },
    "language": {
      processing: "数据加载中...",
      info: "显示第 _start_ 至 _end_ 条,共 _total_ 条记录",
      infoempty: "暂无数据",
      lengthmenu: "显示 _menu_ 条记录",
      paginate: {
        first: "首页",
        previous: "上一页",
        next: "下一页",
        last: "最后一页"
      }
    }
  });

  $datatable.find('tbody').on('click', '.audit', function () {
    var data = table.row($(this).parents('tr')).data();
    var id = data.id;
    var userid = data.userid;
    var group_id = data.group_id;
    var dynamic_id = data.dynamic_id;
    var dynamic_type = data.dynamic_type;
    var type = $(this).data('type');
    audit(id, type, userid, group_id, dynamic_id, dynamic_type)
  });

  // 审核操作
  function audit(id, type, userid, group_id, dynamic_id, dynamic_type) {
    $.post("{{ route('audit.index') }}/" + id, {
      id: id,
      type: type,
      userid: userid,
      group_id: group_id,
      dynamic_id: dynamic_id,
      dynamic_type: dynamic_type,
      _token: "{{ csrf_token() }}",
      _method: "put"
    }, function (data) {
      if (data.result == 0) {
        table.ajax.reload();
        toastr.success("操作成功!");
      }
    });
  }

  $("#is_audit").select2({
    placeholder: "请选择状态",
    minimumresultsforsearch: infinity
  });

  // 搜索
  $("#searchbtn").click(function(){
    table.draw();
  });
</script>
 
<script type="text/javascript">
  $datatable = $("#datatable");
  var table = $datatable.datatable({
    "processing": true,
    "serverside": true,
    "pagelength": 25,
    "lengthmenu": [10, 25, 50, 75, 100, 200],
    "ajax": {
      "url": "{{ route('audit.getlist') }}",
      "data": function (data) {
        data.dynamic_type = "{{ request::get('dynamic_type', 1) }}";
        data.group_id = $("#group_id").val();
        data.dynamic_id = $("#dynamic_id").val();
        data.userid = $("#userid").val();
        data.is_audit = $("#is_audit").val();
        data.t = "{{ time() }}";
      }
    },
    "columns": [
      {"data": "id"},
      {"data": "userid"},
      {"data": "group_id"},
      {"data": "dynamic_type"},
      {"data": "dynamic_id"},
      {"data": "content"},
      {"data": "images"},
      {"data": "money"},
      {"data": "is_audit"},
      {"data": "audited_at"}
    ],
    "columndefs": [
      {
        "render": function (data, type, row) {
          if (data == 1) {
            return "活动";
          } else if (data == 2) {
            return "动态";
          }
        },
        "targets": 3
      },
      {
        "render": function (data, type, row) {
          html = "";
          $.each(data, function (k, v) {
            html += "<a href='" + v.origin + "' target='_blank'><img src='" + v.origin + "' width='160' style='margin-bottom: 2px;'>";
          });
          return html;
        },
        "targets": 6
      },
      {
        "render": function (data, type, row) {
          if (data == 0) {
            return "未审核";
          } else if (data == 1) {
            return "审核通过";
          } else if (data == -1) {
            return "审核不通过";
          }
        },
        "targets": 8
      },
      {
        "render": function (data, type, row) {
          if (row.is_audit == 0) {
            return "<a class='btn btn-primary audit' data-type = 1>通过</a> <a class='btn btn-danger audit' data-type = 2>不通过</a>";
          }
          return "-";
        },
        "targets": 10
      }
    ],
    "createdrow": function (row, data, index) {
      $('td', row).eq(4).attr('style', 'word-break:break-all');
      $('td', row).eq(2).attr('style', 'word-break:break-all');
      $('td', row).eq(5).attr('style', 'word-break:break-all');
    },
    "language": {
      processing: "数据加载中...",
      info: "显示第 _start_ 至 _end_ 条,共 _total_ 条记录",
      infoempty: "暂无数据",
      lengthmenu: "显示 _menu_ 条记录",
      paginate: {
        first: "首页",
        previous: "上一页",
        next: "下一页",
        last: "最后一页"
      }
    }
  });
 
  $datatable.find('tbody').on('click', '.audit', function () {
    var data = table.row($(this).parents('tr')).data();
    var id = data.id;
    var userid = data.userid;
    var group_id = data.group_id;
    var dynamic_id = data.dynamic_id;
    var dynamic_type = data.dynamic_type;
    var type = $(this).data('type');
    audit(id, type, userid, group_id, dynamic_id, dynamic_type)
  });
 
  // 审核操作
  function audit(id, type, userid, group_id, dynamic_id, dynamic_type) {
    $.post("{{ route('audit.index') }}/" + id, {
      id: id,
      type: type,
      userid: userid,
      group_id: group_id,
      dynamic_id: dynamic_id,
      dynamic_type: dynamic_type,
      _token: "{{ csrf_token() }}",
      _method: "put"
    }, function (data) {
      if (data.result == 0) {
        table.ajax.reload();
        toastr.success("操作成功!");
      }
    });
  }
 
  $("#is_audit").select2({
    placeholder: "请选择状态",
    minimumresultsforsearch: infinity
  });
 
  // 搜索
  $("#searchbtn").click(function(){
    table.draw();
  });
</script>

本文主要记录给自己看,不做具体的说明了。

参考链接

datatables 官方文档

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。