ajax实现数据分页查询

用ajax实现对数据库的查询以及对查询数据进行分页,供大家参考,具体内容如下

主页面代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="jquery-1.11.2.min.js"></script>
<style type="text/css">
.dangqian{ background-color:#69F}
</style>
</head>

<body>

<div>
<input type="text" id="key" />
<input type="button" value="查询" id="chaxun" />
</div>

<table width="100%" border="1" cellpadding="0" cellspacing="0">
 <tr>
  <td>代号</td>
  <td>名称</td>
  <td>父级代号</td>
 </tr>
 
 <tbody id="nr">
 
 </tbody> 
</table>
<div id="xinxi">
</div>
</body>

js代码

<script type="text/javascript">
var page = 1; //当前页 定义一个变量 当前页


Load(); //加载数据
LoadXinXi(); //加载分页信息


//查询
$("#chaxun").click(function(){
  page = 1;
  Load(); //加载数据
  LoadXinXi(); //加载分页信息
 })
function Load()
{
 var key = $("#key").val(); //查询条件
 
 $.ajax({
   url:"chuli.php",
   data:{page:page,key:key},
   type:"POST",
   dataType:"JSON",
   success: function(data){
     var str = "";
     for(var k in data)
     {
      str +="<tr><td>"+data[k].AreaCode+"</td><td>"+data[k].AreaName+"</td><td>"+data[k].ParentAreaCode+"</td></tr>";
     }
     $("#nr").html(str);//把数据返回表格
    }
  });
}


functionLoadXinXi()
{
 var str = "";
 var minys = 1;
 var maxys = 1;
 var key = $("#key").val();
 
 //查总页数
 $.ajax({
   async:false,
   url:"zys.php",
   data:{key:key},
   type:"POST",
   dataType:"TEXT",
   success: function(d){
     maxys = d;
    }
  });
 
 str += "<span>总共:"+maxys+"页</span>  ";
 str += "<span id='prev'>上一页</span>";
 
 for(var i=page-2;i<page+3;i++)
 {
  if(i>=minys && i<=maxys)
  {
   if(i==page)
   {
    str += "<span class='dangqian' bs='"+i+"'>"+i+"</span>  ";
   }
   else
   {
    str += "<span class='list' bs='"+i+"'>"+i+"</span>  ";
   }
  
  }
 }
  
 str += "<span id='next'>下一页</span>"; 
 
 $("#xinxi").html(str);
 
 //给上一页添加点击事件
 $("#prev").click(function(){
   page = page-1;
   if(page<1)
   {
    page=1;
   }
   Load(); //加载数据
   LoadXinXi(); //加载分页信息
  })
 //给下一页加点击事件
 $("#next").click(function(){
   page = page+1;
   if(page>maxys)
   {
    page=maxys;
   }
   Load(); //加载数据
   LoadXinXi(); //加载分页信息
  })
 //给中间的列表加事件
 $(".list").click(function(){
   page = parseInt($(this).attr("bs"));
   Load(); //加载数据
   LoadXinXi(); //加载分页信息
  })
}

</script>

处理页面1

<?php
include("DBDA.class.php");
$db = new DBDA();

$key = $_POST["key"];
$num = 20;

$sql = "select count(*) from chinastates where areaname like '%{$key}%'";

$zts = $db->StrQuery($sql);

echo ceil($zts/$num);

处理页面2

<?php
include("DBDA.class.php");
$db = new DBDA();

$page = $_POST["page"];
$key = $_POST["key"];
$num = 20;
$tiao = ($page-1)*$num;

$sql = "select * from chinastates where areaname like '%{$key}%' limit {$tiao},{$num}";

echo $db->JSONQuery($sql);

相关推荐