我有一个客户模块,我有这个客户列表。我正在使用Laravel 5和这个包http://datatables.net/。我用它是因为它有内置的搜索和排序功能。所以发生什么是当我加载页面时,我正在做一个ajax请求来查询我的customers
表中的所有记录,然后使用datatables
包/插件在表中传播所有这些记录。问题是当我有太多的记录,比如2万。页面没有响应。我觉得这太费时间了。这是我的jquery代码:
$.ajax({
url: "api/customer/all",
type: 'GET',
success: function(result){
var myObj = $.parseJSON(result);
//console.log(myObj);
$.each(myObj, function(key,value) {
var t = $('#CustomerList').DataTable();
t.row.add( [
value.id,
value.firstname,
value.lastname,
value.gender,
value.phone_num,
value.postcode,
value.country,
"<a class='btn btn-small btn-info' href='<?php echo URL::to('customer').'/';?>"+value.id+"/edit'><span class='glyphicon glyphicon glyphicon-edit' aria-hidden='true'></span></a>",
"<form method='POST' action='<?php echo URL::to('customer').'/';?>"+value.id+"' accept-charset='UTF-8' class='pull-left' >"+
"<input name='_method' type='hidden' value='DELETE'>"+
"<button type='submit' class='btn btn-warning'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span></button>"+"</form>",
] ).draw();
});
}});
然后路由
Route::get('api/customer/all', 'CustomerController@apiGetCustomers');
控制器功能
//$customers = Customer::orderBy('id', 'desc')->get();
$query = "SELECT * FROM customers ORDER BY id ASC;";
$data = DB::connection('pgsql')->select($query);
return json_encode($data);
你看我以前也使用Eloquent来获取数据,但它处理大量数据很糟糕,所以我使用Query Builder代替。我认为是jquery让它变慢了,因为我可以很好很快速地获取所有数据。怎样才能传播得更快?我正在使用Postgre 9.3 SQL
Dom操作可能非常慢。您可能希望在间隔中添加行,这可能对用户体验更好。因此,也许可以使用setTimeout()并尝试记录数和等待毫秒数。也许值得一试。
(function loadDataTable() {
var data,
curIndex = 0,
t = $('#CustomerList').DataTable(),
AMOUNT_ROWS = 100;
function addMoreRows() {
var i, value, limit = curIndex + AMOUNT_ROWS;
if (limit > data.length) limit = data.length;
for (i = curIndex; i < limit; i++) {
value = data[i];
t.row.add([
value.id,
value.firstname,
value.lastname,
value.gender,
value.phone_num,
value.postcode,
value.country,
"<a class='btn btn-small btn-info' href='<?php echo URL::to('customer').'/';?>" + value.id + "/edit'><span class='glyphicon glyphicon glyphicon-edit' aria-hidden='true'></span></a>",
"<form method='POST' action='<?php echo URL::to('customer').'/';?>" + value.id + "' accept-charset='UTF-8' class='pull-left' >" +
"<input name='_method' type='hidden' value='DELETE'>" +
"<button type='submit' class='btn btn-warning'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span></button>" + "</form>"
]).draw();
curIndex = i + 1;
if (curIndex != data.length) setTimeout(addMoreRows, 200); // give browser time to process other things
}
}
$.ajax({
url: "api/customer/all",
type: 'GET',
success: function(result) {
data = $.parseJSON(result);
addMoreRows();
}
});
}
})();