我有一个客户模块,我有这个客户列表。我正在使用Laravel 5和这个包http://datatables.net/。我用它是因为它有一个内置的搜索和排序。因此,当我加载页面时,我会发出ajax请求来查询customers
表中的所有记录,然后使用datatables
包/插件在表中传播所有记录。问题是我的唱片太多了,大概20000张。页面将不响应。我认为这需要太多的处理。这是我的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);
你看,我以前也在使用雄辩的方法来获取数据,但是处理大量数据很糟糕,所以我改用查询生成器。我认为它慢的是jquery,因为我可以快速地获取所有数据。我怎样才能传播得更快?我用的是Postgre9.3SQL。
最佳答案
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();
}
});
}
})();
关于php - 在数据表jQuery中传播海量数据的更快方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32474262/