当我从日期选择器更改日期时,它碰到了ajax请求,但未过滤我的数据
这是我的潜在客户清单清单视图,其中显示了数据表:
<script>
$(document).ready(function() {
$('#startDate').datepicker();
$('#endDate').datepicker();
var table = $('#myDataTable').DataTable({
processing: true,
serverSide: true,
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
],
ajax: '{{ route('leadData') }}',
columns: [
{data: 'first_name', name: 'first_name'},
{data: 'last_name', name: 'last_name'},
{data: 'number', name: 'number'},
{data: 'email', name: 'email'},
{data: 'studio_id', name: 'studio_id'},
{data: 'created_at', name: 'created_at'},
]
});
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
console.log('data');
var min = $('#startDate').datepicker('getDate');
var max = $('#endDate').datepicker('getDate');
var startDate = new Date(data[5]);
if (min == null && max == null) return true;
if (min == null && startDate <= max) return true;
if (max == null && startDate >= min) return true;
if (startDate <= max && startDate >= min) return true;
return false;
}
);
$('#startDate, #endDate').change( function() {
table.draw();
});
});
这是我用于显示数据表结果的线索控制器方法:
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function leadData() {
$leads = Lead::with('studio')->get();
// dd($leads[0]->created_at);
return Datatables::of($leads)->editColumn('studio_id', function($leads){
$leadname = $leads->studio->name;
return $leadname;
})->make(true);
}
这是我用于更改日期格式的访问器:
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function getCreatedAtAttribute($value) {
return date('m/d/Y', strtotime($this->attributes['created_at']));
}
我的桌子是
销售线索:
id,first_name,last_name,number,电子邮件,studio_id,created_at,updated_at
答案 0 :(得分:1)
您不需要在服务器端更改格式,您可以使用javascript
// set a common class for both id
$('.datepicker').datepicker({
dateFormat: 'yy-mm-dd'
});
var myDataTable = $('#myDataTable').DataTable({
dom: 'Bfrtip',
"oSearch": {"bSmart": false},
processing: true,
serverSide: true,
ajax: {
url: "{{ route('leadData') }}",
type: 'GET',
data: function (d) {
// read start date from the element
d.from = $('#startDate').val();
// read end date from the element
d.to = $('#endDate').val();
}
},
columns: [
{data: 'first_name', name: 'first_name'},
{data: 'last_name', name: 'last_name'},
{data: 'number', name: 'number'},
{data: 'email', name: 'email'},
{data: 'studio_id', name: 'studio_id'},
{data: 'created_at', name: 'created_at'},
],
});
// set on change datepicker
$('.datepicker').on('change', function() {
from = $("#startDate").val();
to = $("#endDate").val();
if(from && to) {
myDataTable.draw();
}
});
您可以像这样使用的服务器端
$startDate = $request->get('startDate');
$endDate = $request->get('endDate');
$query = Lead::with('studio');
if($startDate && $endDate) {
$query->whereDate('lead.created_at', '>=', $startDate)
->whereDate('lead.created_at', '<=', $endDate);
}
$leads = $query->get();