天天看點

頁面滾動重新整理并實時加載資料

<!DOCTYPE html>

<html>

<head>

<title>頁面滾動重新整理并自動加載資料</title>

<meta charset='utf-8' />

<!--引入jquery-->

<script src='./jquery-3.3.1.min.js'></script>

</head>

<!--========================html部分========================-->

<body>

<!--設定一個高于目前浏覽器高度的div-->

<div id='test' style='width:960px;height:2000px;background-color:#aaa;margin:0 auto'>内容區域</div>

<!--後面自動加載的資料存放到此div當中-->

<div id='text' style='width:960px;height:auto;margin:0 auto;background-color:#bbb;'></div>

<!--加載資料時等待過程中用到的gif動畫圖,一開始是隐藏狀态-->

<div id='loading' style='display:none;width:960px;height:30px;auto;margin:0 auto'>

<img style='width:100%;height:100%' src='./logogif.gif' />

</div>

</body>

</html>

<!--========================js部分========================-->

<script>

$(document).ready(function(){

$(window).scroll(function(){

//$(document).scrollTop(); //滾動條位置距頁面頂部的距離

//$(document).height(); //整個頁面的總高度

//$(window).height(); //目前可見視窗的高度

//滾動條位置距頁面頂部的距離 = 文檔的總高度 - 目前視窗的高度時,就意味着已經滾動了一個視窗的高度,及已經到目前視窗的底部

if( $(document).scrollTop() >= $(document).height() - $(window).height() ){ //判斷是否已經滾動到頁面底部

//切換加載動圖的狀态為顯示

$('#loading').css('display','block'); 

//通過ajax加載資料

$.ajax({

type:'post',

url:'./data.php', //這裡請求的一個php檔案

success:function(data){ //當請求成功時執行的回調函數

data = JSON.parse(data); //将php傳回的json資料整理成數組

var str = ''; 

$.each(data,function(i,item){ //周遊出json裡的内容,i辨別目前周遊到第幾條内容,item表示目前周遊的對象 

str += item['name'] + ' ' + item['age'] + ' ' + item['sex']  + '<br />';

});

//将周遊到的内容追加到id為text的div中去 

$('#text').append(str);

//切換加載動圖的狀态為隐藏

$('#loading').css('display','none');

}

});

}

});

});

</script>

================data.php源碼================

<?php

$arr2_str = array();

$arr2_str[0]["name"]="李金";

$arr2_str[0]["age"]=33;

$arr2_str[0]["sex"]="男";

$arr2_str[1]["name"]="熊金菊";

$arr2_str[1]["age"]=23;

$arr2_str[1]["sex"]="女";

echo json_encode($arr2_str); //傳回json資料

?>