jQuery+Ajax+PHP+Mysql实现分页显示数据
index.html
XML/HTML Code
- <script type="text/javascript">
- var curPage = 1; //当前页码
- var total,pageSize,totalPage;
- //获取数据
- function getData(page){
- $.ajax({
- type: 'POST',
- url: 'pages.php',
- data: {'pageNum':page-1},
- dataType:'json',
- beforeSend:function(){
- $("#list ul").append("<li id='loading'>loading...</li>");
- },
- success:function(json){
- $("#list ul").empty();
- total = json.total; //总记录数
- pageSize = json.pageSize; //每页显示条数
- curPage = page; //当前页
- totalPage = json.totalPage; //总页数
- var li = "";
- var list = json.list;
- $.each(list,function(index,array){ //遍历json数据列
- li += "<li><a href='#'>"+array['title']+"</a></li>";
- });
- $("#list ul").append(li);
- },
- complete:function(){ //生成分页条
- getPageBar();
- },
- error:function(){
- alert("数据加载失败");
- }
- });
- }
- //获取分页条
- function getPageBar(){
- //页码大于最大页数
- if(curPage>totalPage) curPage=totalPage;
- //页码小于1
- if(curPage<1) curPage=1;
- pageStr = "<span>共"+total+"条</span><span>"+curPage+"/"+totalPage+"</span>";
- //如果是第一页
- if(curPage==1){
- pageStr += "<span>首页</span><span>上一页</span>";
- }else{
- pageStr += "<span><a href='javascript:void(0)' rel='1'>首页</a></span><span><a href='javascript:void(0)' rel='"+(curPage-1)+"'>上一页</a></span>";
- }
- //如果是最后页
- if(curPage>=totalPage){
- pageStr += "<span>下一页</span><span>尾页</span>";
- }else{
- pageStr += "<span><a href='javascript:void(0)' rel='"+(parseInt(curPage)+1)+"'>下一页</a></span><span><a href='javascript:void(0)' rel='"+totalPage+"'>尾页</a></span>";
- }
- $("#pagecount").html(pageStr);
- }
- $(function(){
- getData(1);
- $("#pagecount span a").live('click',function(){
- var rel = $(this).attr("rel");
- if(rel){
- getData(rel);
- }
- });
- });
- </script>
- </head>
- <body>
- <h1 class="logo"><a href="http://www.freejs.net" title="freejs首页"><img src="../../images/logo.png" height="47" width="500" alt="freejs首页" /></a></h1>
- <div id="main_demo">
- <div align="center"><h2><a href="../../article_biaodan_10.html">jQuery+Ajax+PHP+Mysql实现分页显示数据</a></h2></div>
- <div id="main">
- <div id="list">
- <ul></ul>
- </div>
- <div id="pagecount"></div>
- </div>
pages.php
PHP Code
- <?php
- include_once('conn.php');
- $page = intval($_POST['pageNum']);
- $result = mysql_query("select * from content");
- $total = mysql_num_rows($result);//总记录数
- $pageSize = 6; //每页显示数
- $totalPage = ceil($total/$pageSize); //总页数
- $startPage = $page*$pageSize;
- $arr['total'] = $total;
- $arr['pageSize'] = $pageSize;
- $arr['totalPage'] = $totalPage;
- $query = mysql_query("select * from content order by id asc limit $startPage,$pageSize");
- while($row=mysql_fetch_array($query)){
- $arr['list'][] = array(
- 'id' => $row['id'],
- 'title' => $row['name'],
- );
- }
- //print_r($arr);
- echo json_encode($arr);
- ?>
原文地址:http://www.freejs.net/article_fenye_26.html