jQuery+PHP+ajax實現(xiàn)微博加載更多內(nèi)容列表功能
在一些微博網(wǎng)站上我們經(jīng)??梢钥吹竭@樣的應用,微博內(nèi)容列表上并沒有使用分頁條,而是一次加載一定數(shù)量的記錄顯示在列表頁,當用戶瀏覽到列表頁底部時,可以通過單擊“查看更多”來加載更多記錄。本文將結合jQuery和PHP給大家講述如何實現(xiàn)這種功能。
Ajax加載的基本原理:當頁面載入時,jQuery向后臺請求數(shù)據(jù),PHP通過查詢數(shù)據(jù)庫將最新的幾條記錄顯示在列表頁,在列表頁的底部有個“查看更多”的鏈接,通過觸發(fā)該鏈接,向服務端發(fā)送Ajax請求,后臺PHP程序得到請求參數(shù),并作出響應,獲取數(shù)據(jù)庫相應的記錄并以JSON的形式返回給前臺頁面,前臺頁面jQuery解析JSON數(shù)據(jù),并將數(shù)據(jù)追加到列表頁。其實就是Ajax分頁效果。
首先要引入jquery庫和jquery.more.js插件,jquery.more.js已經(jīng)將許多功能都封裝好了,并提供了參數(shù)配置的功能。
<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.more.js"></script>
xhtml結構如下:
<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">::點擊加載更多內(nèi)容::</a>
</div>
需要指出的是,樣式single_item,get_more是和jquery.more.js插件關聯(lián)的,你也可以取另外的class名字,但是在配置的時候一定要將對應的class寫上。
CSS樣式如下:
#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部分如下:
$(function(){
$('#more').more({'address': 'data.php'})
});
使用很簡單,配置了后臺地址:data.php,來看data.php是怎么處理數(shù)據(jù)的。
PHP部分:
data.php文件:
鏈接數(shù)據(jù)庫:
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接收前臺頁面提交過來的兩個參數(shù),$_POST['last']即開始記錄數(shù),$_POST['amount']即單次顯示記錄數(shù),看SQL語句就明白,其實就是分頁中用到的語句。
然后將查詢的結果以JSON格式輸出,PHP的任務就完成了。
最后來看下jquery.more.js的參數(shù)配置:
'amount' : '10', //每次顯示記錄數(shù) 'address' : 'comments.php', //請求后臺的地址 'format' : 'json', //數(shù)據(jù)傳輸格式 'template' : '.single_item', //html記錄DIV的class屬性 'trigger' : '.get_more', //觸發(fā)加載更多記錄的class屬性 'scroll' : 'false', //是否支持滾動觸發(fā)加載 'offset' : '100', //滾動觸發(fā)加載時的偏移量
相關文章
用PHP獲取Google AJAX Search API 數(shù)據(jù)的代碼
用PHP獲取Google AJAX Search API 數(shù)據(jù)的代碼2010-03-03

