用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="https://www.jb51.net/jquery-1.11.2.min.js"></script> <style type="text/css"> .dangqian{ background-color:#69F} </style> </head> <body> <div> <input type="text" /> <input type="button" value="查询" /> </div> <table cellpadding="0" cellspacing="0"> <tr> <td>代号</td> <td>名称</td> <td>父级代号</td> </tr> <tbody> </tbody> </table> <div> </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>上一页</span>"; for(var i=page-2;i<page+3;i++) { if(i>=minys && i<=maxys) { if(i==page) { str += "<span bs='"+i+"'>"+i+"</span> "; } else { str += "<span bs='"+i+"'>"+i+"</span> "; } } } str += "<span>下一页</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);