smarty+php+ajax 簡單無刷新分頁

    簡介

    分頁,無非就是從數據庫中獲得我們想查詢的數據,再加以處理即可!

    ① 確定數據總數($count)

    ② 每頁顯示數據條數($pageSize)

    ③ 分多少頁($pageCount)

    ④ 上一頁($pagePrev)

    ⑤ 下一頁($pageNext)

    ⑥ 判斷越界問題

    ⑦ 偏移量($offset)

    ⑧ sql語句($sql = "select * from goods limit $offset,$pageSize";)

    簡單歸簡單,我們還得考慮實際的應用。例如:如果你正在土豆網看《火影忍者》,下面一個評論吸引了你,你點擊“下一頁”後整個頁面都刷新,我勒個去,《火影忍者》也刷沒了,只能再從頭開始看,這樣的情況是不是令你十分厭惡。再想想,如果當你點擊“下一頁”時,只有評論的部分刷新,你的視頻根本沒有受到影響,那是不是很完美呢!

    想要無刷新,第一個想到Ajax;前臺都是HTML+JS,後臺php+smarty組合,那我們就直接進入主題:

    

    文件結構

    wKioL1Q6h9yRGlm9AABJFHoHYjg697.jpg

    ① Smarty模板文件 官網地址:http://www.smarty.net/

    ② /templates     自定義的文件夾  page.htpl模板文件,用於存放分頁數據及鏈接

    ③ page.html      前臺顯示頁面   js觸發

    ④ page.php       數據庫處理   smarty數據處理

    ⑤ public.js      Ajax對象的封裝

    

    程序流程

    ① 前端page.html傳遞page參數(不傳遞後臺頁面也會默認賦值)

        (前端主要的作用:顯示、發出Ajax請求)

    ② php頁面數據庫操作,$sql分頁語句查詢出分頁所需的數據

    ③ 載入smarty模板,將參數assign傳遞到page.htpl模板頁

    ④ 模板頁導入數據、遍歷數據  將上、下頁加入超鏈接及js事件

    ⑤ smarty fetch()方法讀取模板頁數據 賦值給變量  變量再響應給Ajax客戶端

    ⑥ 前臺接收


    代碼

    page.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
        <title>無刷新分頁</title>
        <script language="javascript" src="public.js"></script>
        <script language="javascript">
        function display(page){
            $.get('page.php','page='+page,function(msg){
                $('content').innerHTML = msg;
            });
        }
        window.onload = function(){
            display(1);
        };
        </script>
    </head>
    
    <body>
        <div id="content"></div>
    </body>
</html>

    public.js

(function(){
    //1、用於得到一個DOM元素
    //定義了一個$函數 作用域有局部
    var $ = function(id){
        return document.getElementById(id);
    };
    
    //2、用於得到一個Ajax對象
    //將$看作函數對象,init爲屬性,值爲函數體
    $.init = function(){
        try{return new XMLHttpRequest()}catch(e){} 
        try{return new ActiveXObject('Microsoft.XMLHTTP')}catch(e){}
        alert('請更改新瀏覽器!');
    };
    //用於發送Ajax get請求
    $.get = function(url,data,callback,type){
        var xhr = $.init();
        if (data != null){//傳遞參數、只發出請求
            url = url+'?'+data;
        }
        xhr.open('get',url);
        xhr.setRequestHeader('If-Modified-Since','0');//解決get緩存問題
        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4 && xhr.status == 200){
                //當沒有指定傳值類型時,默認爲字符串
                if (type == null){
                    type = 'text';
                }
                //判斷語句指定三種接收形式
                if (type == 'text'){
                    callback(xhr.responseText);
                }
                if (type == 'xml'){
                    callback(xhr.responseXML);
                }
                if (type == 'json'){
                    callback(eval("("+xhr.responseText+")"));
                }
            }
    };
    xhr.send(null);
    };
        //增大其作用域全局變量  window方法的$屬性  賦值爲$  閉包寫法
        window.$ = $;
})();

    page.php

<?php
    mysql_connect('localhost','root','111111');
    mysql_select_db('shop');
    mysql_query('set names gb2312');
    //爲查詢結果增加新字段 num
    $sql = "select * from sw_goods";
    $result = mysql_query($sql);
    $count = mysql_num_rows($result);//獲得總行數,與mysql_num_rows()類似
    $page = isset($_GET['page'])?$_GET['page']:1;//獲取當前頁碼,默認1
    $pageSize = 5;//頁尺寸  每頁顯示多少條數據
    $pageCount = ceil($count/$pageSize);//計算總頁面
    $pagePrev = $page - 1;//上一頁頁碼
    $pageNext = $page + 1;//下一頁頁碼
    if ($pagePrev < 1) $pagePrev = 1;  //判斷頁碼越界
    if ($pageNext > $pageCount) $pageNext = $pageCount;
    if ($page < 1) $page = 1;   //判斷當前頁頁碼越界
    if ($page > $pageCount) $page = $pageCount;
    $offset = ($page -1)*$pageSize; //偏移量    
    //相對於當前頁來講的
    $sql = "select * from sw_goods limit $offset,$pageSize"; //order by id asc 默認/desc
    $result = mysql_query($sql);//查詢那一頁的結果集
    $num = mysql_num_rows($result);
    $data = array();
    for ($i=0;$i<$num;$i++){
    //遍歷五次,每次獲得一個數組array('good_id'=>'','goods_name'=>'','goods_price'=>'')
    //形成一個二維數組
    $data[] = mysql_fetch_assoc($result);
    }
    mysql_close();
    //***************************************************************************
    include('Smarty/Smarty.class.php');
    $smarty = new Smarty();
    $smarty -> assign('data',$data);
    $smarty -> assign('count',$count);
    $smarty -> assign('pageCount',$pageCount);
    $smarty -> assign('page',$page);
    $smarty -> assign('pagePrev',$pagePrev);
    $smarty -> assign('pageNext',$pageNext);
    $smarty -> assign('pageCount',$pageCount);
    $str = $smarty -> fetch('page.htpl');//獲取模板裏面的數據,賦值給變量,再傳遞給Ajax
    對象
    header("content-type:text/html;charset=gb2312");
    echo $str;

    page.htpl

<!--htpl是當作模板來用的擴展名-->
<!--分頁模板-->
 <style type="text/css">
        *{
            margin:0px;
            padding:0px;
        }
        body{
            text-align:center;
        }
        table{
            width:650px;
            margin:0px auto;
            margin-top:20px;
        }
        tr{
            background-color:#ffffff;
            height:30px;
            font-size:12px;
        }
</style>
<table cellspacing="1" cellpadding="4" bgcolor="#336699">
    <tr>
        <td>序號</td>
        <td>商品名稱</td>
        <td>商品價格</td>
        <td>商品數量</td>
    </tr>
    {foreach from = $data item = 'value'}
    <tr>
        <td>{counter}</td>
        <td>{$value['goods_name']}</td>
        <td>{$value['goods_price']}</td>
        <td>{$value['goods_number']}</td>
    </tr>
    {/foreach}
    <tr>    
        <td colspan = '4'>
        共{$count}條數據
        共{$pageCount}頁
        當前第{$page}頁
        <a href="#" onclick="display(1)">首頁</a>
        <a href="#" onclick="display({$pagePrev})">上一頁</a>
        <a href="#" onclick="display({$pageNext})">下一頁</a>
        <a href="#" onclick="display({$pageCount})">末頁</a>
        </td>
    </tr>
</table>

    最後的分頁效果:

    wKiom1Q6jaCD0Jh3AAEoKd5TsRE696.jpg

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章