页面滚动刷新并实时加载数据

爱唱歌的和尚:废话不多说,直接上干货~!


<!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数据
?>

猜你喜欢

转载自blog.csdn.net/weixin_42007636/article/details/80036187