这是一个比较详细的ajax分页加载demo,增删改查接口已经完备,现增加详细的备注
includes/Db.class.php 数据库连接文件
这里采用pdo链接,PDO与Mysqli的选择
<?php // 连接数据库 class Db { static public function getDB() { try { $pdo = new PDO(DB_DSN, DB_USER, DB_PWD); $pdo->setAttribute(PDO::ATTR_PERSISTENT, true); // 设置数据库连接为持久连接 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 设置抛出错误 $pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); // 设置当字符串为空转换为 SQL 的 NULL $pdo->query('SET NAMES utf8'); // 设置数据库编码 } catch (PDOException $e) { exit('数据库连接错误,错误信息:'. $e->getMessage()); } return $pdo; } } ?>includes/Model.class.php 数据库操作文件
<?php /** * 数据库操作类库 */ class Model { /** * 数据库添加操作 * @param string $tName 表名 * @param array $field 字段数组 * @param array $val 值数组 * @param bool $is_lastInsertId 是否返回添加ID * @return int 默认返回成功与否,$is_lastInsertId 为true,返回添加ID */ public function add($tName, $field, $val, $is_lastInsertId=FALSE) { try { if (!is_array($field) || !is_array($val)) exit($this->getError(__FUNCTION__, __LINE__)); $pdo = Db::getDB(); $field = $this->formatArr($field); $val = $this->formatArr($val, false); if (!$is_lastInsertId) { $row = $pdo->exec("INSERT INTO {$tName} ({$field}) VALUES ({$val})"); $pdo = null; return $row; } else { $pdo->exec("INSERT INTO {$tName} ({$field}) VALUES ({$val})"); $lastId = $pdo->lastInsertId(); $pdo = null; return $lastId; } } catch (PDOException $e) { exit($e->getMessage()); } } /** * 数据库修改操作 * @param string $tName 表名 * @param array $field 字段数组 * @param array $val 值数组 * @param string $condition 条件 * @return int 受影响的行数 */ public function update($tName, $fieldVal, $condition) { try { if (!is_array($fieldVal) || !is_string($tName) || !is_string($condition)) exit($this->getError(__FUNCTION__, __LINE__)); $pdo = Db::getDB(); foreach ($fieldVal as $k=>$v) { $upStr .= $k . '=' . '\'' . $v . '\'' . ','; } $upStr = rtrim($upStr, ','); $row = $pdo->exec("UPDATE {$tName} SET {$upStr} WHERE {$condition}"); $pdo = null; return $row; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 数据库删除操作(注:必须添加 where 条件) * @param string $tName 表名 * @param string $condition 条件 * @return int 受影响的行数 */ public function del($tName, $condition) { try { if (!is_string($tName) || !is_string($condition)) exit($this->getError(__FUNCTION__, __LINE__)); $pdo = Db::getDB(); $row = $pdo->exec("DELETE FROM {$tName} WHERE {$condition}"); return $row; $pdo = null; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 返回表总个数 * @param string $tName 表名 * @param string $condition 条件 * @return int */ public function total($tName, $condition='') { try { if (!is_string($tName)) exit($this->getError(__FUNCTION__, __LINE__)); $pdo = Db::getDB(); $re = $pdo->query("SELECT COUNT(*) AS total FROM {$tName}" . ($condition=='' ? '' : ' WHERE ' . $condition)); foreach ($re as $v) { $total = $v['total']; } return $total; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 数据库删除多条数据 * @param string $tName 表名 * @param string $field 依赖字段 * @param array $ids 删除数组 * @return int 受影响的行数 */ public function delMulti($tName, $field, $ids) { try { if (!is_string($tName) || !is_array($ids)) exit($this->getError(__FUNCTION__, __LINE__)); $pdo = Db::getDB(); foreach ($ids as $v) { $delStr .= $v . ','; } $delStr = rtrim($delStr, ','); $row = $pdo->exec("DELETE FROM {$tName} WHERE {$field} IN ({$delStr})"); $pdo = null; return $row; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 获取表格的最后主键(注:针对 INT 类型) * @param string $tName 表名 * @param string $primaryName 依赖字段 * @return int */ public function lastId($tName, $primaryName) { try { if (!is_string($tName) || !is_string($primaryName)) exit($this->getError(__FUNCTION__, __LINE__)); $pdo = Db::getDB(); $re = $pdo->query("SELECT {$primaryName} FROM {$tName} ORDER BY {$primaryName} DESC LIMIT 1"); $lastId = null; foreach ($re as $v) { $lastId = $v[$primaryName]; } $pdo = null; return $lastId; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 返回全部数据,返回 PDOStatement 对象 * @param string $sql * @return PDOStatement */ public function getAll($sql) { try { if (!is_string($sql)) exit($this->getError(__FUNCTION__, __LINE__)); $pdo = Db::getDB(); $result = $pdo->query($sql); $pdo = null; return $result; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 检查数据是否已经存在(依赖条件),可用于用户注册 * @param string $tName 表名 * @param string $field 依赖的字段 * @return bool */ public function isExists($tName, $condition) { try { if (!is_string($tName) || !is_string($condition)) exit($this->getError(__FUNCTION__, __LINE__)); $pdo = Db::getDB(); $result = $pdo->query("SELECT COUNT(*) AS total FROM {$tName} WHERE {$condition}"); foreach ($result as $v) { $b = $v['total']; } $pdo = null; if ($b) { return true; } else { return false; } } catch (PDOException $e) { exit($e->getMessage()); } } /** * 检查数据是否已经存在(依赖 int 主键) * @param string $tName 表名 * @param string $primary 主键 * @param int $id 主键值 * @return bool */ public function isExistsByIntPrimary($tName, $primary, $id) { try { if (!is_string($tName) || !is_string($primary) || !is_int($id)) exit($this->getError(__FUNCTION__, __LINE__)); $pdo = Db::getDB(); $result = $pdo->query("SELECT COUNT(*) AS total FROM {$tName} WHERE {$primary} = ". $id); foreach ($result as $v) { $b = $v['total']; } $pdo = null; if ($b) { return true; } else { return false; } } catch (PDOException $e) { exit($e->getMessage()); } } /** * 预处理添加数据(推荐使用) * @param string $tableName 表格名 * @param array $fieldArr 字段名数组 * @param array $valArr 字段值数组 * @param bool $mult 是否添加多条数据,如果是那么 $valArr 为二维数组 * @return int 返回添加的记录数,添加单条为1,多条为多 */ public function insert($tableName, $fieldArr, $valArr, $mult=FALSE) { try { if (!is_string($tableName) || !is_array($fieldArr) || !is_array($valArr) || !is_bool($mult)) exit($this->getError(__FUNCTION__, __LINE__)); $pdo = Db::getDB(); $fields = $this->formatArr($fieldArr); $arrCount = count($fieldArr); $mark = $this->formatMark($arrCount); $stmt = $pdo->prepare("INSERT INTO {$tableName} ({$fields}) VALUES ({$mark})"); if (!$mult) { $row = $stmt->execute($valArr); // 添加单条数据 } else { $row = 0; for ($i=0; $i<count($valArr); $i++) { if ($stmt->execute($valArr[$i])) { $row++; } } } $pdo = null; return $row; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 预处理删除(注:针对主键为 INT 类型,推荐使用) * @param string $tName 表名 * @param string $primary 主键字段 * @param int or array or string $ids 如果是删除一条为 INT,多条为 array,删除一个范围为 string * @return int 返回受影响的行数 */ public function remove($tName, $primary, $ids, $mult=FALSE) { try { if (!is_string($tName) || !is_string($primary) || (!is_int($ids) && !is_array($ids) && !is_string($ids)) || !is_bool($mult)) exit($this->getError(__FUNCTION__, __LINE__)); $pdo = Db::getDB(); $stmt = $pdo->prepare("DELETE FROM {$tName} WHERE {$primary}=?"); if (!$mult) { $stmt->bindParam(1, $ids); $row = $stmt->execute(); } else { if (is_array($ids)) { $row = 0; foreach ($ids as $v) { $stmt->bindParam(1, $v); if ($stmt->execute()) { $row++; } } } elseif (is_string($ids)) { if (!strpos($ids, '-')) exit($this->getError(__FUNCTION__, __LINE__)); $split = explode('-', $ids); if (count($split)!=2 || $split[0]>$split[1]) exit($this->getError(__FUNCTION__, __LINE__)); $i = null; $count = $split[1]-$split[0]+1; for ($i=0; $i<$count; $i++) { $idArr[$i] = $split[0]++; } foreach ($idArr as $id) { $idStr .= $id . ','; } $idStr = rtrim($idStr, ','); $row = $pdo->exec("DELETE FROM {$tName} WHERE {$primary} in ({$idStr})"); } } return $row; $pdo = null; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 返回单条数据 * @param string $tName 表名 * @param string $condition 条件 * @param string or array $fields 返回的字段,默认是* * @return PDOStatement */ public function getOne($tName, $condition, $fields="*") { try { if (!is_string($tName) || !is_string($condition) || !is_string($fields)) exit($this->getError(__FUNCTION__, __LINE__)); $pdo = Db::getDB(); $data = $pdo->query("SELECT {$fields} FROM {$tName} WHERE {$condition} LIMIT 1"); $pdo = null; return $data; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 返回全部数据 * @param string $tName 表名 * @param string $fields 返回字段,默认为* * @param string $condition 条件 * @param string $order 排序 * @param string $limit 显示个数 * @return PDOStatement */ public function fetchAll($tName, $fields='*', $condition='', $order='', $limit='') { try { if (!is_string($tName) || !is_string($fields) || !is_string($condition) || !is_string($order) || !is_string($limit)) exit($this->getError(__FUNCTION__, __LINE__)); $fields = ($fields=='*' || $fields=='') ? '*' : $fields; $condition = $condition=='' ? '' : " WHERE ". $condition ; $order = $order=='' ? '' : " ORDER BY ". $order; $limit = $limit=='' ? '' : " LIMIT ". $limit; $pdo = Db::getDB(); $re = $pdo->query("SELECT {$fields} FROM {$tName} {$condition} {$order} {$limit}"); return $re; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 格式化数组(表结构和值) * @param array $field * @param bool $isField * @return string */ private function formatArr($field, $isField=TRUE) { if (!is_array($field)) exit($this->getError(__FUNCTION__, __LINE__)); if ($isField) { foreach ($field as $v) { $fields .= $v.','; } } else { foreach ($field as $v) { $fields .= '\''.$v.'\''.','; } } $fields = rtrim($fields, ','); return $fields; } /** * 格式化问号,批量替换掉 * @param int $count 数量 * @return string 返回格式化后的字符串 */ private function formatMark($count) { if (!is_int($count)) exit($this->getError(__FUNCTION__, __LINE__)); if ($count==1) return '?'; for ($i=0; $i<$count; $i++) { $str .= '?,'; } return rtrim($str, ','); } /** * 错误提示 * @param string $fun * @return string */ private function getError($fun, $line) { return __CLASS__ . '->' . $fun . '() line<font color="red">'. $line .'</font> ERROR!'; } } ?>includes/ajaxPage.class.php ajax处理文件(核心部分)
<?php ini_set("error_reporting","E_ALL & ~E_NOTICE"); //屏蔽掉未定义变量报错 class ajaxPage { private $total; //数据表中总记录数 private $listRows;//每页显示行数 private $limit; private $uri; private $pageNum; //页数 private $config=array('header'=>"个记录", "prev"=>"上一页", "next"=>"下一页", "first"=>"首 页", "last"=>"尾 页"); private $listNum=8; public $html; /* * $total * $listRows */ public function __construct($total, $listRows=10, $pa=""){ $this->total=$total; $this->listRows=$listRows; $this->uri=$this->getUri($pa); $this->page=!empty($_GET["page"]) ? $_GET["page"] : 1; $this->pageNum=ceil($this->total/$this->listRows); $this->limit=$this->setLimit(); } private function setLimit(){ return ($this->page-1)*$this->listRows.", {$this->listRows}"; } private function getUri($pa){ $url=$_SERVER["REQUEST_URI"].(strpos($_SERVER["REQUEST_URI"], '?')?'':"?").$pa; $parse=parse_url($url); if(isset($parse["query"])){ parse_str($parse['query'],$params); unset($params["page"]); $url=$parse['path'].'?'.http_build_query($params); } return $url; } public function __get($args){ if($args=="limit") return $this->limit; else return null; } /**private function __get($args){ if($args=="limit") return $this->limit; else return null; }**/ private function start(){ if($this->total==0) return 0; else return ($this->page-1)*$this->listRows+1; } private function end(){ return min($this->page*$this->listRows,$this->total); } private function first(){ if($this->page==1) $html.=''; else $html.=" <a href='javascript:setPage(1)'>{$this->config["first"]}</a> "; return $html; } private function prev(){ if($this->page==1) $html.=''; else $html.=" <a href='javascript:setPage(". ($this->page-1) .")'>{$this->config["prev"]}</a> "; return $html; } private function pageList(){ $linkPage=""; $inum=floor($this->listNum/2); for($i=$inum; $i>=1; $i--){ $page=$this->page-$i; if($page<1) continue; $linkPage.=" <a href='javascript:setPage({$page})'>{$page}</a> "; } $linkPage.=" {$this->page} "; for($i=1; $i<=$inum; $i++){ $page=$this->page+$i; if($page<=$this->pageNum) $linkPage.=" <a href='javascript:setPage({$page})'>{$page}</a> "; else break; } return $linkPage; } private function next(){ if($this->page==$this->pageNum) $html.=''; else $html.=" <a href='javascript:setPage(". ($this->page+1) .")'>{$this->config["next"]}</a> "; return $html; } private function last(){ if($this->page==$this->pageNum) $html.=''; else $html.=" <a href='javascript:setPage(". ($this->pageNum) .")'>{$this->config["last"]}</a> "; return $html; } private function goPage(){ return ' <input type="text" onkeydown="javascript:if(event.keyCode==13){var page=(this.value>'.$this->pageNum.')?'.$this->pageNum.':this.value;setPage(page)}" value="'.$this->page.'" style="width:25px"><input type="button" value="GO" onclick="javascript:var page=(this.previousSibling.value>'.$this->pageNum.')?'.$this->pageNum.':this.previousSibling.value;setPage(page)"> '; } function fpage($display=array(0,1,2,3,4,5,6,7,8)){ $html[0]=" 共有<b>{$this->total}</b>{$this->config["header"]} "; $html[1]=" 每页显示<b>".($this->end()-$this->start()+1)."</b>条,本页<b>{$this->start()}-{$this->end()}</b>条 "; $html[2]=" <b>{$this->page}/{$this->pageNum}</b>页 "; $html[3]=$this->first(); $html[4]=$this->prev(); $html[5]=$this->pageList(); $html[6]=$this->next(); $html[7]=$this->last(); $html[8]=$this->goPage(); $fpage=''; foreach($display as $index){ $fpage.=$html[$index]; } return $fpage; } } ?>js/ajax.js js拼接文件
function Ajax(recvType){ var aj=new Object(); aj.recvType=recvType ? recvType.toUpperCase() : 'HTML' //HTML XML aj.targetUrl=''; aj.sendString=''; aj.resultHandle=null; aj.createXMLHttpRequest=function(){ var request=false; //window对象中有XMLHttpRequest存在就是非IE,包括(IE7,IE8) if(window.XMLHttpRequest){ request=new XMLHttpRequest(); if(request.overrideMimeType){ request.overrideMimeType("text/xml"); } //window对象中有ActiveXObject属性存在就是IE }else if(window.ActiveXObject){ var versions=['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Msxml2.XMLHTTP.7.0','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP']; for(var i=0; i<versions.length; i++){ try{ request=new ActiveXObject(versions[i]); if(request){ return request; } }catch(e){ request=false; } } } return request; } aj.XMLHttpRequest=aj.createXMLHttpRequest(); aj.processHandle=function(){ if(aj.XMLHttpRequest.readyState == 4){ if(aj.XMLHttpRequest.status == 200){ if(aj.recvType=="HTML") aj.resultHandle(aj.XMLHttpRequest.responseText); else if(aj.recvType=="XML") aj.resultHandle(aj.XMLHttpRequest.responseXML); } } } aj.get=function(targetUrl, resultHandle){ aj.targetUrl=targetUrl; if(resultHandle!=null){ aj.XMLHttpRequest.onreadystatechange=aj.processHandle; aj.resultHandle=resultHandle; } if(window.XMLHttpRequest){ aj.XMLHttpRequest.open("get", aj.targetUrl); aj.XMLHttpRequest.send(null); }else{ aj.XMLHttpRequest.open("get", aj.targetUrl, true); aj.XMLHttpRequest.send(); } } aj.post=function(targetUrl, sendString, resultHandle){ aj.targetUrl=targetUrl; if(typeof(sendString)=="object"){ var str=""; for(var pro in sendString){ str+=pro+"="+sendString[pro]+"&"; } aj.sendString=str.substr(0, str.length-1); }else{ aj.sendString=sendString; } if(resultHandle!=null){ aj.XMLHttpRequest.onreadystatechange=aj.processHandle; aj.resultHandle=resultHandle; } aj.XMLHttpRequest.open("post", targetUrl); aj.XMLHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); aj.XMLHttpRequest.send(aj.sendString); } return aj; }config.inc.php 数据库配置文件
<?php header('Content-Type:text/html;Charset=utf-8'); define('ROOT_PATH', dirname(__FILE__)); // 网站根目录 define('UPDIR', '/upload/'); // 上传文件路径 define('DB_DSN', 'mysql:host=localhost;dbname=ajaxtest'); define('DB_USER', 'root'); define('DB_PWD', 'root'); // 自动加载文件类 function __autoload($className) { require_once ROOT_PATH . '/includes/'. ucfirst($className) .'.class.php'; } ?>article.php 文章调取处理文件
<?php /** * $Id: article.php */ require_once './config.inc.php'; $m = new Model(); $page = new ajaxPage($m->total('article'),20); // $m->total('article') 获取 article 表的记录数;10为每页显示十条 $result = $m->fetchAll('article', '*', '', '', $page->limit); // 调用model类中的fetchAll方法,查询数据 echo '<table align="center" border="1" width="1100" style="border-collapse:collapse;font-size:14px;" bordercolor="#666">'; echo '<caption><h1>华强电子网资讯</h1></caption>'; echo '<tr height="25"><th>ID</th><th>Title</th><th>Author</th><th>Source</th><th>Date</th></tr>'; foreach ($result as $v) { echo "<tr height='21'><td align='center'>{$v['id']}</td><td>{$v['title']}</td><td align='center'>{$v['author']}</td><td align='center'>{$v['source']}</td><td align='center'>{$v['date']}</td></tr>"; } echo '<tr><td align="right" colspan="5">'.$page->fpage().'</td></tr>'; echo '</table>'; ?>index.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=UTF-8"> <script type="text/javascript" src="js/ajax.js"></script> <!-- 载入 Ajax 类库 --> <title>Ajax 实现无刷新分页加载</title> <style type="text/css"> body { font-size:12px; } </style> </head> <body> <div id="fpage">数据加载中...</div> </body> </html> <script type="text/javascript"> //页面访问优化处理 /** * setPage(url) 根据 url 从 article.php 中获取数据 * @param int pageNum 页码 * @return string */ var cache=new Array(); // 缓存变量,当数据被访问过之后放置在缓存中,加快访问速度 function setPage(pageNum) { var fpage = document.getElementById('fpage'); // 获取 fpage 对象 // 如果缓存中存在数据,那么直接从缓存中读取;如果不存在数据,那么就从数据库中读取,并把数据存入缓存 if (typeof(cache[pageNum])=='undefined') { var ajax = Ajax(); ajax.get('article.php?page='+pageNum, function(data){ fpage.innerHTML = data; // fpage对象的内容是从 article.php 中取来的 cache[pageNum] = data; }) } else { fpage.innerHTML = cache[pageNum]; } } setPage(1); // 默认执行 </script>数据库设计
源码地址:http://pan.baidu.com/s/1eR8rer4