php-ajax实现无刷新分页

一个简单的分页类-page.class.php

<?php
class page{
	private $total;	//总页数
	private $size;	//每页记录数
	private $url;	//URL地址
	private $page;	//当前页码
	/**
	 * 构造函数
	 * @param $total 总记录数
	 * @param $size  每页记录数
	 * @param $url   URL地址
	 */
	public function __construct($total,$size,$url=''){
		//计算页数,向上取整
		$this->total = ceil($total / $size);
		//获得当前页码
		$this->page = $this->getNowPage();
		//每页记录数
		$this->size = $size;
		//为URL添加GET参数
		$this->url = $this->setUrl($url);
	}
	/**
	 * 获得当前页码
	 */
	private function getNowPage(){
		$page = empty($_GET['page']) ? 1 : $_GET['page'];
		if($page < 1){
			$page = 1;
		}else if($page > $this->total){
			$page = $this->total;
		}
		return $page;
	}
	/**
	 * 为URL添加GET参数,去掉page参数
	 */
	private function setUrl($file){
		$params = $_GET;
		unset($params['page']);
		$url = http_build_query($params);
		return $url ? "$file?$url&" : "$file?";
	}
	/**
	 * 获得分页导航
	 */
	public function getPageList(){
		//总页数不超过1时直接返回空结果
		if($this->total<=1){
			return '';
		}
		//拼接分页导航的HTML
		$html = '';
		if($this->page>4){
			$html = "<a href=\"#\" onclick=\"getGoods('{$this->url}page=1')\">1</a> ... ";
		}
		for($i=$this->page-3,$len=$this->page+3; $i<=$len && $i<=$this->total; $i++){
			if($i>0){
				if($i==$this->page){
					$html .= " <a href=\"#\" onclick=\"getGoods('{$this->url}page=$i')\" class=\"curr\">$i</a>";
				}else{ 
					$html .= " <a href=\"#\" onclick=\"getGoods('{$this->url}page=$i')\">$i</a> ";
				}
			}
		}
		if($this->page+3<$this->total){
			$html .= " ... <a href=\"#\" onclick=\"getGoods('{$this->url}page={$this->total}')\">{$this->total}</a>";
		}
		//返回拼接结果
		return $html;
	}
	/**
	 * 获得 SQL中的 limit
	 */
	 public function getLimit(){
		if($this->total==0){
			return '0, 0';
		}
		return ($this->page - 1) * $this->size . ", {$this->size}";
	 }
}

从数据库中获取数据-data.php

<?php
header("Content-Type:text/html;charset=utf-8");
//引入分页类
include "./page.class.php";
//使用PDO连接数据库
try{
	//实例化PDO创建
	$pdo = new PDO("mysql:host=127.0.0.1;dbname=shop;charset=utf8","root","root");
	//设置字符集编码
	$pdo->query("set names utf8");
	//SQL预处理语句
	$stmt1 = $pdo->query("select count(*) from `ecs_goods`");
	//实例化分页类对象
	$total = $stmt1->fetchColumn();
	$per = 3;
	$page = new Page($total,$per,'./data.php');
	$stmt = $pdo->prepare("select goods_id,goods_name,market_price from ecs_goods limit ".$page->getLimit());
	//获得页码列表信息
	$pagelist = $page->getPageList();
	//执行SQL预处理语句
	$stmt->execute();
}catch(Exception $e){
	echo $e->getMessage().'<br>';
}
//查询结果
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
//将分页信息追加到$data数组中
$data[] = $pagelist;
//输出页面
echo json_encode($data);

前台模板文件-index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>商品列表</title>
    <script>
        function getGoods(url) {
            // 通过Ajax对象获得分页信息
            var obj = new XMLHttpRequest();
            obj.onreadystatechange = function() {
                if (obj.readyState == 4 && obj.status == 200) {
                    // 接受服务器端的响应信息
                    eval("var info="+obj.responseText);
                    // 拼接输出的字符串
                    var dataList = "<tr><td>ID</td><td>名称</td><td>价格</td></tr>";
                    for (var i = 0; i < info.length - 1; i++) {
                        dataList += "<tr><td>" + info[i].goods_id + "</td>";
                        dataList += "<td>" + info[i].goods_name + "</td>";
                        dataList += "<td>" + info[i].market_price + "</td></tr>";
                    }

                    dataList += "<tr><td colspan=3>" + info[info.length - 1] + "</td></tr>";
                    // 将字符串写入网页
                    document.getElementById('result').innerHTML = dataList;
                }
            }
            obj.open("get", url);
            obj.send();
        }

        window.onload = function() {
            getGoods('./data.php');
        }
    </script>
    <style type="text/css">
       a{border:1px solid #fff;text-decoration:none;color:#999;padding:2px 4px;margin:0
        2px;line-height:20px;}
       a:hover{background:#f0f0f0;border:1px solid #999;}
      .curr{background:#f0f0f0;border:1px solid #999;}
       table{ width:600px;cellspacing:2px; background-color:#333333;}
       tr{height:30px;}
       td{width:200px; background-color:#FFFFFF; text-align:center;}
       h2{ text-align:center}
     </style>
</head>
<body>
    <h2>Ajax实现商品列表无刷新分页</h2>
    <table id="result" align="center">
    </table>
    <div id="bottom" align="center"><div>

    <script type="text/javascript">
        //获取一个随机数,用于判断无刷新分页效果
        var num = "随机数值:";
         num += Math.ceil(Math.random()*10);
         //将随机数字符串写入到网页中
        document.getElementById('bottom').innerHTML = num;
    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_42195688/article/details/80372632
今日推荐