对于在 l5 中使用 paginate 进行无限滚动,我发现了很多文章,但它们都使用这个 paginate() 函数,因为它们使用来自 db 的结果集,但我从 googlefontapi 获取数据作为 json,所以当我在 json 中使用 paginate() 时它会导致错误并且也在数组中。我的代码
public function index(){
$url = "https://www.googleapis.com/webfonts/v1/webfonts?key=!";
$result = json_decode(file_get_contents( $url ))->paginate(10);
$font_list = "";
foreach ( $result->items as $font )
{
$font_list[] = [
'font_name' => $font->family,
'category' => $font->category,
'variants' => implode(', ', $font->variants),
// subsets
// version
// files
];
}
return view('website_settings')->with('data', $font_list);
}
错误是
Call to undefined method stdClass::paginate()
还有其他方法可以实现吗
对于您的情况,您需要使用Illluminate\Support\Collection
。然后我们就可以通过Illuminate\Support\Collection
的一个实例Illuminate\Pagination\Paginator
类得到我们的Illuminate\Pagination\Paginator
实例返回。确保use Illuminate\Pagination\Paginator
.
use Illuminate\Pagination\Paginator;
然后,根据结果创建一个集合:
$collection = collect(json_decode($file_get_contents($url), true));
最后,构建分页器。
$paginator = new Paginator($collection, $per_page, $current_page);
或者写一行,因为这就是你滚动的方式:
$paginator = new Paginator(collect(json_decode($file_get_contents($url), true)));
如果需要,您还可以缓存该集合,并且仅在请求不是 XHR 请求时(例如在页面加载期间)重新加载它。当您需要保留时这很有用API
请求减少到最低限度,并且通常还有助于加快请求的性能,因为任何 HTTP 请求都会有与之相关的延迟。
希望这有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)