PHP+Ajax 实现分页技术

10 篇文章 0 订阅
本文介绍了一种基于PHP和Ajax技术实现的分页查询方案,通过两个PHP文件sn_inq.php和sn_show.php的配合使用,实现了动态加载数据的功能。用户可以通过前端表单输入查询条件,后端则根据这些条件进行数据检索并返回分页结果。
摘要由CSDN通过智能技术生成

基于php和ajax的分页技术代码,下面有两个php文件,一个是sn_inq.php,另一个是sn_show.php,前一个php文件调用后一个php文件,实现ajax分页,运行sn_inq即可实现效果,不过得修改数据库哦。具体代码如下:红色标注的地方要特别注意修改哦!

我的数据库名是inv,表名是sn,字段有:sn_id,sn_plant,sn_sales,sn_act,sn_type,sn_sts.....

1.sn_inq.php 

//getFormValue 用于获取表单中所有输入控件的值,并将输入值组成一个字符串传到服务器。

<script type="text/javascript"> 
function getFormValue(form){
 var str='';
 var ft,fv;
 for (var i=0; i<form.elements.length; i++){
  fv = form.elements[i];
  ft = fv.type.toLowerCase();
  switch(ft){
   case 'select-one':
    str+=fv.name+'='+escape(fv.value)+'&';
    break;
   case 'radio':
    if (fv.checked){
     str+=fv.name+'='+escape(fv.value)+'&';
    }
    break;
   case 'checkbox':
    if (fv.checked){
     str+=fv.name+'='+escape(fv.value)+'&';
    }
    break;
   case 'text':
    str+=fv.name+'='+escape(fv.value)+'&';
    break;
   case 'password':
    str+=fv.name+'='+escape(fv.value)+'&';
    break;
   case 'hidden':
    str+=fv.name+'='+escape(fv.value)+'&';
    break;
   case 'textarea':
    str+=fv.name+'='+escape(fv.value)+'&';
    break;
   default:
    break;
  }
 }
 return str.split(//s/).join('')
}
 

//showcomment(page) 用于显示分页数据,被查询按钮onclick 事件调用, url为后台处理数据并输出XML格式数据的文件url。


function showcomment(page) {

Str ='';
 if (document.all.per_records){
  Str += "show_per="+document.all.per_records.value;
 }
 var x = new Ajax('statusid', 'XML');
 url = 'sn_show.php?page='+page+'&'+getFormValue(document.form1)+Str;
 
 x.get(url , function(s) {
  if(s.lastChild){
   getbyid("show").innerHTML = "Loading……";
   getbyid("show").innerHTML = s.lastChild.firstChild.nodeValue;
   removeLoading(document.getElementById("show"));
  }
  else{
   document.form1.submit();
  }
 });
}

//displayLoading用于显示Loading,提示用户等待

function displayLoading(element) {
    var image = document.createElement("img");
    image.setAttribute("src","progressbar.gif");
    image.setAttribute("title","loading...");
    var text = document.createTextNode("loading……");
    element.appendChild(image);
    element.appendChild(text);
}

//removeLoading用于去掉Loading

function removeLoading(element){
 var image = element.getElementsByTagName("img");
 for(var i=0;i<image.length;i++){
  element.removeChild(image[i]);
 }
}

//ajax

function Ajax(statusId, recvType) {
 var aj = new Object();
 displayLoading(document.getElementById("show"));
 var clientHeight = scrollTop = 0;
 if(navigator.userAgent.toLowerCase().indexOf('opera') > -1) {
  clientHeight = document.body.clientHeight;
  scrollTop = document.body.scrollTop;
 } else {
  clientHeight = document.documentElement.clientHeight;
  scrollTop = document.documentElement.scrollTop;
 }
 if(document.getElementById(statusId)) {
  aj.statusId = document.getElementById(statusId);
  document.getElementById(statusId).style.top = 10+"px";
 } else {
  var divElement = document.createElement("DIV");
  divElement.id = "xspace-tipDiv";
  divElement.className = "xspace-ajaxdiv";
  divElement.style.cssText = "width:200px; height:40px; line-height: 40px; text-align: center;";
  divElement.style.left = 10+"px";
  divElement.style.top = 10+"px";//(clientHeight +scrollTop - 60)
  divElement.id = statusId;
  document.body.appendChild(divElement);
  aj.statusId = divElement;
 }
 aj.targetUrl = '';
 aj.sendString = '';
 aj.recvType = recvType ? recvType : 'HTML';//HTML XML
 aj.resultHandle = null;
 aj.createXMLHttpRequest = function() {
  var request = false;
  if(window.XMLHttpRequest) {
   request = new XMLHttpRequest();
   if(request.overrideMimeType) {
    request.overrideMimeType('text/xml');
   }
  } else if(window.ActiveXObject) {
   var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.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) {
     //alert(e.message);
    }
   }
  }
  return request;
 }
 aj.XMLHttpRequest = aj.createXMLHttpRequest();
 aj.processHandle = function() {
  aj.statusId.style.display = '';
  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.statusId.style.display = 'none';
   } else {
    aj.statusId.innerHTML = xml_http_load_failed;
   }
  }
 }

 aj.get = function(targetUrl, resultHandle) {
  aj.targetUrl = targetUrl;
  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", targetUrl, true);
         aj.XMLHttpRequest.send();
  }
 }

 aj.post = function(targetUrl, sendString, resultHandle) {
  aj.targetUrl = targetUrl;
  aj.sendString = sendString;
  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;
}

function getbyid(id) {
 if (document.getElementById) {
  return document.getElementById(id);
 } else if (document.all) {
  return document.all[id];
 } else if (document.layers) {
  return document.layers[id];
 } else {
  return null;
 }

</script>

<?php

//注意:此处如果有filesedset的话,form表单一定要放在fieldset里面,否则出错。
echo '<form name="form1" action="" method="post">
     <table cellpadding="0" cellspacing="1">
   <tr>
    <th class="criteria">SN</th>
    <td>
     <input type="text" name="sn_id_1" value="'.$_POST['sn_id_1'].'" size="16" maxlength="8"/> to
     <input type="text" name="sn_id_2" value="'.$_POST['sn_id_2'].'" size="16" maxlength="8"/>
           <input type="button" name="sn_submit" value="Search"  onClick="showcomment(1)"/>
    </td>
   </tr>
  </table>
 </form>
<div id="show"></div>';

?>

2.sn_show.php:

<?php
//page function
function  showpage($total,$num){

 global $page,$pagenav,$middle,$pagenum,$offset,$prepg,$nextpg;

 $page=isset($_REQUEST['page'])?intval($_REQUEST['page']):1;        //假如不存在page,那么页数就是1。
 $middle = '4'; //每层分页条显示4个分页连接
 //$num=10;                                      //每页显示10条数据
 $pagenum=ceil($total/$num);                                    //获得总页数,也是最后一页
 $page=min($pagenum,$page);//获得首页
 $prepg=$page-1;//上一页
 $nextpg=($page==$pagenum ? 0 : $page+1);//下一页
 $offset=($page-1)*$num;
 $pagenav.='<span style="font-size:110%">';

 if ($pagenum != 1){
  if ($page == 1){
   $pagenav.=' <img style="vertical-align: middle;" src="./images/page_first.gif" background="red" alt="first page"></img>';
   $pagenav.=' <img style="vertical-align: middle;" src="./images/page_prev.gif" alt="previous page"></img>';
   $pagenav.=' <a href="javascript:;" οnclick="javascript:showcomment('.$nextpg.');"><img style="vertical-align: middle;" src="./images/page_next.gif" alt="next page"></img></a> ';
   $pagenav.=' <a href="javascript:;" οnclick="javascript:showcomment('.$pagenum.');"><img style="vertical-align: middle;" src="./images/page_last.gif" alt="last page"></img></a> ';
  }else if($page == $pagenum){
   $pagenav.=' <a href="javascript:;" οnclick="javascript:showcomment(1);"><img style="vertical-align: middle;" src="./images/page_first.gif" alt="first page"></img></a> ';
   $pagenav.=' <a href="javascript:;" οnclick="javascript:showcomment('.$prepg.');"><img style="vertical-align: middle;" src="./images/page_prev.gif" alt="previous page"></img></a> ';
   $pagenav.=' <img style="vertical-align: middle;" src="./images/page_next.gif" alt="next page"></img> ';
   $pagenav.=' <img style="vertical-align: middle;" src="./images/page_last.gif" alt="last page"></img>';
  }else{
   $pagenav.=' <a href="javascript:;" οnclick="javascript:showcomment(1);"><img style="vertical-align: middle;" src="./images/page_first.gif" alt="first page"></img></a> ';
   $pagenav.=' <a href="javascript:;" οnclick="javascript:showcomment('.$prepg.');"><img style="vertical-align: middle;" src="./images/page_prev.gif" alt="previous page"></img></a> ';
   $pagenav.=' <a href="javascript:;" οnclick="javascript:showcomment('.$nextpg.');"><img style="vertical-align: middle;" src="./images/page_next.gif" alt="next page"></img></a> ';
   $pagenav.=' <a href="javascript:;" οnclick="javascript:showcomment('.$pagenum.');"><img style="vertical-align: middle;" src="./images/page_last.gif" alt="last page"></img></a> ';
  }

  $pagenav .= SP2.'<span style="border: 1px solid #BBB; padding: 2px;"> Total <span style="color: red; font-weight: bold;">'.number_format($pagenum, 0).'</span> Pages | <span style="color: red; font-weight: bold;">'.number_format($total, 0).'</span> Records </span>'.SP5;
  for($h=($page-$middle<1?1:$page-$middle);$h<=($page+$middle>$pagenum?$pagenum:$page+$middle);$h++){

     if($h==$page){
    $pagenav.="<b> $h </b>";
     }else{
    $pagenav.="&nbsp;&nbsp;<a href=/"javascript:showcomment(".$h.");/">".iconv('gb2312','gb2312',$h)."</a>&nbsp;&nbsp;";
     }
  }
  $pagenav.="&nbsp;&nbsp;&nbsp;&nbsp;";
  $pagenav.=iconv('gb2312','gb2312','Go ');
  //$pagenav.='<input type="text" name="tz_page" id="tz_page" size="1" value="'.$page.'" οnkeydοwn="show();" />';
  $pagenav.="<select id='JumpSelect' name='NowPage' size='1' οnchange=/"showcomment(this.value);/">";
  for ($i = 1; $i <= $pagenum;$i++){
   if($page == $i){
    $pagenav.= "<option value='".$i."' selected>".$i."</option>";
   }else{
    $pagenav.= "<option value='".$i."' >".$i."</option>";
   }
  }
  $pagenav.="</select></span>";
  $pagenav.="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type='button' value='Show' οnclick='showcomment(1)'></input>";
  $pagenav.="<input type='text' name='per_records' size='1' value='".$num."'></input>";
  return $pagenav;
 }
}

//connect to database
function db_link()
{
 $access_id = "root";
 $db_name   = "inv";
 @ $db = mysql_connect('localhost', $access_id, '831025') or
  die("Could not connect to database. Please contact with IT supporting team ASAP.");
  mysql_query("SET NAMES 'GBK'");
 mysql_select_db($db_name);
 return $db;
}
$link = db_link();

//get inquiry criteria,用 POST取得数据也行
$sn_id_1 = $_REQUEST['sn_id_1'];
$sn_id_2 = $_REQUEST['sn_id_2'];

 

$show_per       = $_REQUEST['show_per']; //自行修改每页显示记录数
if ($show_per != ''){
 $num = $show_per;
}
else{
 $num = 10;
// 每页默认显示10条记录
}

  
//inquiry total pages
$sn_sql = "SELECT * FROM sn WHERE 1 ";
if ($sn_id_1 != ''){
 $sn_sql .= "AND sn_id >= '".$sn_id_1."' ";
}
if ($sn_id_2 != ''){
 $sn_sql .= "AND sn_id <= '".$sn_id_2."' ";
}
$sn_sql .= "ORDER BY sn_id DESC ";
 
$sn_res = mysql_query($sn_sql);
$total  = mysql_num_rows($sn_res);
 
//show page
$pageshow = showpage($total,$num);

//inquiry current page
$sn_sql .= " limit $offset,$num";
$sn_res = mysql_query($sn_sql);
$sn_num = mysql_num_rows($sn_res);

//output inquiry result as XML
header("Content-Type: text/xml");
if($total > 0){
echo  '<?xml version="1.0" encoding="gb2312"?>';
echo  '<root>';
echo  '<![CDATA[';
echo  '<fieldset class="inquiry">
    <legend>LIST</legend>
    <table class="list">
      <tr>
    <th class="header">No</th>
    <th class="header">SN</th>
    <th class="header">Plant</th>
    <th class="header">Sales</th>
    <th class="header">Act</th>
    <th class="header">Type</th>
    <th class="header">Status</th>
    <th class="header">Release Date</th>
    <th class="header">Approve Date</th>
    <th class="header">Reject Date</th>
    <th class="header">Cancel Date</th>
    <th class="header">Close Date</th>
   </tr>';
   $num = $offset;
   for ($i = 0; $i < $sn_num; $i++) {
    $sn_row = mysql_fetch_array($sn_res);
    if ($i % 2 == 0) {
     echo '<tr class="even" style="cursor:hand" >';
    }else{
     echo '<tr class="odd" style="cursor:hand" >';
    }
    echo'<td class="list center">'.($num+1).'</td>
      <td class="list right blue">'.$sn_row['sn_id'].'</td>
      <td class="list center">'.$sn_row['sn_plant'].'</td>
      <td class="list right">'.$sn_row['sn_sales'].'</td>
      <td class="list center red">'.$sn_row['sn_act'].'</td>
      <td class="list center">'.$sn_row['sn_type'].'</td>
      <td class="list center">'.$sn_row['sn_sts'].'</td>
      <td class="list left">'.substr($sn_row['sn_rel_date'],0,10).'</td>
      <td class="list left">'.substr($sn_row['sn_apv_date'],0,10).'</td>
      <td class="list left">'.substr($sn_row['sn_rej_date'],0,10).'</td>
      <td class="list left">'.substr($sn_row['sn_can_date'],0,10).'</td>
      <td class="list left">'.substr($sn_row['sn_cls_date'],0,10).'</td>
        </tr>';
    $num++;
   }
echo   '</table>';
echo   '<div>'.$pageshow.'</div>';
echo   '</fieldset>';
echo   ']]>';
echo   '</root>';  
}else{
 echo 'find nothing';
}

?>

附1:progressbar.gif :   

附2:images文件中图片如下:

page_first:,page_last:,page_prev:,page_next:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值