Laravel Ajax滾動分頁加載的實(shí)現(xiàn)

在進(jìn)行l(wèi)aravel開發(fā)項(xiàng)目的時(shí)候,我們可能需要用到下拉滾動刷新的方式加載頁面。那么在laravel中要怎么實(shí)現(xiàn)呢,下面介紹一個(gè)簡單的方法:

控制器
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;

class PostController extends Controller
{

    public function myPost(Request $request)
    {
        $posts = Post::paginate(6);  

        if ($request->ajax()) {
            $view = view('data',compact('posts'))->render();
            return response()->json(['html'=>$view]);
        }

        return view('my-post',compact('posts'));
    }

}
blade視圖文件

resources/view/my-post.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 分頁滾動加載</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <link  rel="stylesheet">
    <style type="text/css">
        .ajax-load{
            background: #e1e1e1;
            padding: 10px 0px;
            width: 100%;
        }
    </style>
</head>
<body>

<div class="container">
    <h2 class="text-center">Laravel 分頁滾動加載</h2>
    <br/>
    <div class="col-md-12" id="post-data">
        @include('data')
    </div>
</div>

<div class="ajax-load text-center" style="display:none">
    <p>加載更多……</p>
</div>

<script type="text/javascript">
    var page = 1;
    $(window).scroll(function() {
        if($(window).scrollTop() + $(window).height() + 1>= $(document).height()) {
            page++;
            loadMoreData(page);
        }
    });

    function loadMoreData(page){
        $.ajax(
            {
                url: '?page=' + page,
                type: "get",
                beforeSend: function()
                {
                    $('.ajax-load').show();
                }
            })
            .done(function(data)
            {
                //console.log(data.html);
                if(data.html == " "){
                    $('.ajax-load').html("沒有數(shù)據(jù)了……");
                    return;
                }
                $('.ajax-load').hide();
                $("#post-data").append(data.html);
            })
            .fail(function(jqXHR, ajaxOptions, thrownError)
            {
                alert('服務(wù)未響應(yīng)……');
            });
    }
</script>

</body>
</html>

resources/view/data.php

@foreach($posts as $post)
<div>
    <h3><a href="">{{ $post->title }}</a></h3>
    <p>{{ str_limit($post->description, 400) }}</p>

    <div class="text-right">
        <button class="btn btn-success">Read More</button>
    </div>

    <hr style="margin-top:5px;">
</div>
@endforeach
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容