Select2 supports pagination when using remote data through the pagination
key that comes out of processResults
.
For infinite scrolling, the pagination
object is expected to have a more
property which is a boolean (true
or false
). This will tell Select2 whether it should load more results when reaching the bottom, or if it has reached the end of the results.
{
results: [array, of, results],
pagination: {
more: true
}
}
In your case, you have the ability to shape your results. So you can actually change your JSON response to match the expected format, which means you won't even need to use processResults
.
如果修改ajax.data
函数以返回页码,则Select2可以将页码传递为page
.
data: function(params) {
return {
term: params.term || "",
page: params.page || 1
}
},
然后你就可以使用Input::get('page')
来获取页面.您可以使用(page - 1) * resultCount
计算要跳过的结果总数,在您的例子中,resultCount
是25
.这将允许您修改查询,将LIMIT
和OFFSET
组合起来,以获得所需的结果.
$page = Input::get('page');
$resultCount = 25;
$offset = ($page - 1) * $resultCount;
您可以使用以下查询生成LIMIT
/OFFSET
查询(基于this Stack Overflow question.
$breeds = Breed::where('name', 'LIKE', '%' . Input::get("term"). '%')->orderBy('name')->skip($offset)->take($resultCount)->get(['id',DB::raw('name as text')]);
所以现在$breeds
将只包含请求的结果.剩下要做的唯一一件事就是根据Select2的预期来调整响应.您可以通过判断结果总数并查看是否超出限制来确定是否有更多页面.
$count = Breed::count();
$endCount = $offset + $resultCount;
$morePages = $endCount > $count;
So now $morePages
should be a boolean, which is exactly what Select2 is looking for in pagination.more
. Now you just need to shape the response to match the format I mentioned earlier.
$results = array(
"results" => $breeds,
"pagination" => array(
"more" => $morePages
)
);
And then rendering that
return response()->json($results);
Putting everything together, you get this for JavaScript
$("#breed_id").select2({
placeholder: 'Breed...',
width: '350px',
allowClear: true,
ajax: {
url: '',
dataType: 'json',
data: function(params) {
return {
term: params.term || '',
page: params.page || 1
}
},
cache: true
}
});
以下是你的控制器
if ($request->ajax())
{
$page = Input::get('page');
$resultCount = 25;
$offset = ($page - 1) * $resultCount;
$breeds = Breed::where('name', 'LIKE', '%' . Input::get("term"). '%')->orderBy('name')->skip($offset)->take($resultCount)->get(['id',DB::raw('name as text')]);
$count = Breed::count();
$endCount = $offset + $resultCount;
$morePages = $endCount > $count;
$results = array(
"results" => $breeds,
"pagination" => array(
"more" => $morePages
)
);
return response()->json($results);
}