主頁 > 知識庫 > 在Laravel中使用DataTables插件的方法

在Laravel中使用DataTables插件的方法

熱門標簽:拉薩打電話機器人 沈陽人工智能電銷機器人公司 寶安400電話辦理 智能外呼電銷系統(tǒng) 電銷機器人-快迭智能 合肥外呼系統(tǒng)app h5 地圖標注 高識別電銷機器人 哈爾濱400電話辦理到易號網

DataTables 是一個 jQuery 的表格插件,記錄一下在 Laravel 中使用的常用功能和用法,比如 ajax 獲取數據,自定義搜索,效果展現,選項說明等等,有一些細節(jié)記錄下來方便以后查看。

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 發(fā) ajax 請求及一些選項設置

columnDefs 用來自定義每個字段如何展現,可以封裝自己的展現邏輯,也可以獲取到這一行各個字段的值。

createdRow 可以改變創(chuàng)建每一行的行為,比如修改這一行的樣式等等。

table.draw() 方法可以重新發(fā)起 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 "動態(tài)";
          }
        },
        "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: "請選擇狀態(tài)",
    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 "動態(tài)";
          }
        },
        "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: "請選擇狀態(tài)",
    minimumResultsForSearch: Infinity
  });
 
  // 搜索
  $("#searchBtn").click(function(){
    table.draw();
  });
/script>

本文主要記錄給自己看,不做具體的說明了。

參考鏈接

dataTables 官方文檔

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • PHP框架Laravel插件Pagination實現自定義分頁
  • 推薦幾款用 Sublime Text 開發(fā) Laravel 所用到的插件
  • laravel yajra插件 datatable的使用詳解

標簽:巴中 山東 張家口 梅州 林芝 威海 成都 泰州

巨人網絡通訊聲明:本文標題《在Laravel中使用DataTables插件的方法》,本文關鍵詞  在,Laravel,中,使用,DataTables,;如發(fā)現本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《在Laravel中使用DataTables插件的方法》相關的同類信息!
  • 本頁收集關于在Laravel中使用DataTables插件的方法的相關信息資訊供網民參考!
  • 推薦文章