我正在尝试使用自定义过滤器过滤数据表,假设我想使用“标题”列进行过滤: 在我的控制器端点中我这样做了:
public function getDatatableIndex(Request $request)
{
if ($request->ajax()) {
$model= Post::query();
if ($request['title'] ?? false) {
$model->where('title', 'LIKE', "%{$request['title']}%");
}
$data = PostResource::collection($model->get())->resolve();
$dataTable = DataTables::of($data)
->addColumn('#', function ($row) {
static $order = 0;
return ++$order;
});
$dataTable->addColumn('actions', function ($row) {
$data['id'] = $row['id'];
$data['actions'] = $this->table_data['actions'];
return view('dashboard.post.parts.actions', $data)->render();
})
->rawColumns(['#', 'actions'])
->escapeColumns(['*']);
return $dataTable->make(true);
}
}
在js脚本中我这样做了:
var table = $("#kt_datatable_example_1").DataTable({
processing: true,
searching: false,
serverSide: true,
// ajax: route,
ajax: {
url: route,
data: ajaxFilter
},
columns: columns });
$("#apply-filters").click(function () {
console.log($("#title").val()); // this will log the title in the console correctly
table.draw();
});
var ajaxFilter = function (d) {
d.title = $("#title").val();
};
在这里我注意到一件事,那就是标题不是通过请求发送的,但如果我这样做了
ajax: {
url: route,
data: {
title: "test title"
}
},
然后就可以工作了。
有什么建议或解决方案吗,因为我尝试了很多方法,但没有任何效果。
这是我的例子。我把搜索功能放在上面,就像 Marius 先生在评论中所说的那样。
$(document).ready(function () {
// Setup - add a text input to each footer cell
$('#title').each(function () {
var title = $(this).text();
$(this).html('<input style="width:100%;" type="text" placeholder="Search ' + title + '" />');
});
// DataTable
var table = $('#example1').DataTable({
fixedColumns: {
right: 1
},
initComplete: function () {
// Apply the search
this.api()
.columns()
.every(function () {
var that = this;
$('input', this.footer()).on('keyup change clear', function () {
if (that.search() !== this.value) {
that.search(this.value).draw();
}
});
});
},
});
});