1. 程式人生 > >簡單實現滾動載入資料庫資料

簡單實現滾動載入資料庫資料

<!DOCTYPE html >
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>測試</title>
    <script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
</head>

<body onload="getRec(1)">
<div id="table">
    <table width="100%" border="0" cellpadding="10" cellspacing="10" id="ttb">

    </table>
</div>
<div id="txt" style="text-align:center;color:dimgrey;"></div>
<script type="text/javascript">
    var curpage = 2;
    $(function () {
        $(window).scroll(function () {
            // 滾動條位置
            var documentTop = $(document).scrollTop();
            var windowHeight = $(window).height();
            var documentHeight = $(document).height();
            //當 documentTop >= (documentHeight-windowHeight) 說明滾動條已經滾動到底部了
            if (documentTop >= (documentHeight - windowHeight)) {
                // 1 Ajax 獲取後臺資料
                // 2 將獲取的資料按格式形成HTML程式碼
                // 3 將生成的程式碼放進Table標籤
                getRec(curpage);
                // 4 頁碼加1
                curpage = curpage + 1;
            }
        })
    });

    function getRec(PG) {
        var tableTxt = "";
        $.ajax({
            url: "/getrec/",
            type: "post",
            data: {'PG': PG},
            dataType: "json",
            success: function (data) {
                if(data["rec"].length==0){
                    $('#txt').html("沒有更多了");
                }else{
                for (var i = 0; i < data["rec"].length; i++) {
                    tableTxt = "<tr>" +
                        "<td>" + data["rec"][i][0] + "</td>" +
                        "<td>" + data["rec"][i][1] + "</td>" +
                        "<td>" + data["rec"][i][2] + "</td>" +
                        "<td><img src='/media/" + data["rec"][i][3] + "' width='300' height='120'/></td>" +
                        "</tr>";
                    $('#ttb').append(tableTxt);
                }}
            }
        });
    }
</script>

</body>

</html>