在一些微博网站上我们经常可以看到这样的应用,微博内容列表上并没有使用分页条,而是一次加载一定数量的记录显示在列表页,当用户浏览到列表页底部时,可以通过单击“查看更多”来加载更多记录。本文将结合jQuery和PHP给大家讲述如何实现这种功能。
Ajax加载的基本原理:当页面载入时,jQuery向后台请求数据,PHP通过查询数据库将最新的几条记录显示在列表页,在列表页的底部有个“查看更多”的链接,通过触发该链接,向服务端发送Ajax请求,后台PHP程序得到请求参数,并作出响应,获取数据库相应的记录并以JSON的形式返回给前台页面,前台页面jQuery解析JSON数据,并将数据追加到列表页。其实就是Ajax分页效果。
首先要引入jquery库和jquery.more.js插件,jquery.more.js已经将许多功能都封装好了,并提供了参数配置的功能。
1
2
|
<script type=
"text/javascript"
src=
"jquery.js"
></script>
<script type=
"text/javascript"
src=
"jquery.more.js"
></script>
|
xhtml结构如下:
1
2
3
4
5
6
7
8
9
10
|
<
div
id
=
"more"
>
<
div
class
=
"single_item"
>
<
div
class
=
"element_head"
>
<
div
class
=
"date"
></
div
>
<
div
class
=
"author"
></
div
>
</
div
>
<
div
class
=
"content"
></
div
>
</
div
>
<
a
href
=
"javascript:;"
class
=
"get_more"
>::点击加载更多内容::</
a
>
</
div
>
|
需要指出的是,样式single_item,get_more是和jquery.more.js插件关联的,你也可以取另外的class名字,但是在配置的时候一定要将对应的class写上。
CSS样式如下:
1
2
3
4
5
6
7
8
9
|
#more{
margin
:
10px
auto
;
width
:
560px
;
border
:
1px
solid
#999
;}
.single_item{
padding
:
20px
;
border-bottom
:
1px
dotted
#d3d3d3
;}
.author{
position
:
absolute
;
left
:
0px
;
font-weight
:
bold
;
color
:
#39f
}
.date{
position
:
absolute
;
right
:
0px
;
color
:
#999
}
.content{
line-height
:
20px
; word-break: break-
all
;}
.element_head{
width
:
100%
;
position
:
relative
;
height
:
20px
;}
.get_more{
margin
:
10px
;
text-align
:
center
}
.more_loader_spinner{
width
:
20px
;
height
:
20px
;
margin
:
10px
auto
;
background
:
url
(loader.gif)
no-repeat
;}
|
以上CSS是本例中定制的,当然,大家可以在实际项目中定制不同的样式。注意,more_loader_spinner是定义加载动画图片的。
jQuery部分如下:
1
2
3
|
$(
function
(){
$(
'#more'
).more({
'address'
:
'data.php'
})
});
|
使用很简单,配置了后台地址:data.php,来看data.php是怎么处理数据的。
PHP部分:
data.php文件:
链接数据库:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
require_once
(
'connect.php'
);
$last
=
$_POST
[
'last'
];
$amount
=
$_POST
[
'amount'
];
$user
=
array
(
'demo1'
,
'demo2'
,
'demo3'
,
'demo3'
,
'demo4'
);
$query
=mysql_query(
"select * from say order by id desc limit $last,$amount"
);
while
(
$row
=mysql_fetch_array(
$query
)) {
$sayList
[] =
array
(
'content'
=>
$row
[
'content'
],
'author'
=>
$user
[
$row
[
'userid'
]],
'date'
=>
date
(
'm-d H:i'
,
$row
[
'addtime'
])
);
}
echo
json_encode(
$sayList
);
|
data.php接收前台页面提交过来的两个参数,$_POST['last']即开始记录数,$_POST['amount']即单次显示记录数,看SQL语句就明白,其实就是分页中用到的语句。
然后将查询的结果以JSON格式输出,PHP的任务就完成了。
最后来看下jquery.more.js的参数配置:
1
2
3
4
5
6
7
|
'amount'
:
'10'
,
//每次显示记录数
'address'
:
'comments.php'
,
//请求后台的地址
'format'
:
'json'
,
//数据传输格式
'template'
:
'.single_item'
,
//html记录DIV的class属性
'trigger'
:
'.get_more'
,
//触发加载更多记录的class属性
'scroll'
:
'false'
,
//是否支持滚动触发加载
'offset'
:
'100'
,
//滚动触发加载时的偏移量
|