jq ajax 点击按钮异步加载更多

时间:2022-12-22 22:19:03

挺简单的异步加载 代码都有备注!

流程挺简单的:查询数据库查出内容,写分页,前台输出,js异步请求服务器,控制器处理返回! 然后是按分页请求!每次请求几页这样。具体大伙去研究研究吧!

// info/list.html 页面代码 要加载的内容摘出来新建文件放进去

<volist name="dynamic" id="v">
<li>
<a href="{:U('info/show',array('id'=>$v['id']))}" class="flexdis">
<div class="pic-comwh">
<img src="{:attach($v['img'],article)}">
</div>
<div class="cont flexbox">
<p class="title">{$v['title']}</p>
<p class="text">
{$v['seo_desc']|syssubstr=150}
</p>
<time>{$v['time']|date='m-d H:i',###}</time>
</div>
</a>
</li>
</volist>

//控制器代码

  public function index() {
if(IS_AJAX){
$map['cate_id'] = 9;
$map['status'] = 1;
$count = M('article')->where($map)->count('id');
$_GET['p']=$this->_request('p','intval'); //从前台获取当前处于第几页
$pagesize = 3;//每页3个
$pager = $this->_pager($count, $pagesize);
$dynamic = M('article')->where($map)->limit($pager->firstRow . ',' . $pager->listRows)->order('ordid asc')->select();
$pager = $pager->fshow();
$this->assign(array('pager' => $pager, 'dynamic' => $dynamic, 'count' => $count));
$temp=$this->fetch('info:list');//获取模板内容(加载的内容)
$this->ajaxReturn(1,'',$temp,ceil($count/$pagesize));//返回数据给前端 标识,提示,数据,页数
}
$this->display();
}

//前台页面代码

<pre name="code" class="html"><include file="public:head"/>{/*网站顶部*/}
<body>
<include file="index:header"/>{/*网站头部*/}
<div class="banner_info" style="background-image:url(__STATIC__/index/uploads/info01.jpg);">
<img src="__STATIC__/index/uploads/info02.png" class="move-circle"></div>
<div class="info_main info_list">
<div class="location">当前位置: <a href="{:U('index/index')}">首页</a> > <a href="javascript:void(0);">动态</a> </div>
<!-- 这个地方是容器,内容在info/list.html-->
<ul class="c_b J_ajx" data-p="1" data-max="1"></ul>
<a href="javascript:void(0)" class="more">加载更多</a>
</div>

<!--这里放js代码-->

<include file="index:footer"/>{/*网站底部*/}
</body>
</html>
 

//js异步加载代码 (重要)

<script type='text/javascript'>
$(function () {
$(".more").eq(0).trigger('click'); //默认先加载1页 (不写进入页面则空白,点击才加载)
})
$(".more").click(function () {
var box=$('.J_ajx'),max=box.attr('data-max'),p=box.attr('data-p'); //容器,总页数,当前页
if(p!=1&&(max==1||p>max)){ //页数超过总页数阻止运行
$(".more").html('没有更多');
return false;
}
var ob={
p:p
};
$.ajax({
url: "{:U('info/index')}",
type: 'post',
data: ob,
dataType: 'json',
success: function (data) {
if (data.status == 1) {
box.append(data.data);
box.attr('data-p',parseInt(p)+1);//当前页+1
box.attr('data-max',data.dialog);
}
}
});
});

</script>