使用AJAX實現分頁


Fenye.html

<!DOCTYPE html>
<html>
<head>
    <title>分頁</title>
</head>
<script type="text/javascript">
/**
* AJAX
* 1.創建ajax對象
* 2.建立連接
* 3.判斷ajax准備狀態及狀態碼
* 4.發送請求
*/
function showList(pageNow){

    //創建ajax對象
    var xmlHttp = new XMLHttpRequest();

    //建立連接
    xmlHttp.open('get','./AJAX_Fenye.php?pageNow='+pageNow);

    //判斷ajax准備狀態及狀態碼
    xmlHttp.onreadystatechange = function(){

        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            //alert(xmlHttp.readyState);
            document.getElementById('result').innerHTML = xmlHttp.responseText;
        }
    }

    //發送請求
    xmlHttp.send(null);
}

//默認顯示第1頁
window.onload = function(){

    showList(1);
}

</script>
<body>
<input type="text">
<div id="result">
    <!-- 此處顯示信息! -->
</div>
</body>
</html>

 

Fenye.php

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AJAX分頁</title>
</head>
<body>

<?php 
//以下php代碼可封裝調用,參數為pageNow


//鏈接數據庫
@mysql_connect('localhost','root','');
@mysql_select_db('empmanage');
@mysql_query('set name utf8');

//獲取總記錄數
$rs = mysql_query('select count(*) from emp');
$rows = mysql_fetch_row($rs);
$recordCount = $rows[0];

//每頁顯示多少條pageSize
$pageSize = 5;

//總頁數 = 總記錄/每頁顯示多少
$pageCount=ceil($recordCount/$pageSize);

//獲取當前頁  三元運算 若不存在pageNow則默認顯示第1頁
$pageNow = isset($_GET['pageNow'])? $_GET['pageNow']:1;

if ($pageNow < 1) {
    $pageNow = 1;
}elseif ($pageNow > $pageCount) {
    $pageNow = $pageCount;
}

//起始位置  每頁從第幾條數據顯示
$pageStart = ($pageNow-1)*$pageSize;

//從哪條開始顯示,限制每頁顯示幾條
$sql = "select * from emp limit $pageStart,$pageSize";

//鏈接數據庫
$rs = mysql_query($sql);

//以上php代碼可封裝調用,參數為pageNow  返回查詢到的數據$rs

 ?>

 <table bordercolor="green" border="1">
     <tr>
         <th>ID</th>
         <th>姓名</th>
         <th>郵箱</th>
         <th>等級</th>
     </tr>

<?php  
//循環取出數據
while ($rows = mysql_fetch_assoc($rs)) { 
echo "
        <tr>
            <td>{$rows['id']}</td>
            <td>{$rows['name']}</td>
            <td>{$rows['email']}</td>
            <td>{$rows['level']}</td>
         </tr>
    ";
}
?>
 <tr>
     <td colspan='4'>
     <?php
         //分頁頁碼  調用js中的showList()方法  此處$i=$pageNow
             for ($i=1; $i <= $pageCount; $i++) { 
                 echo "<a href = 'javascript:void(0)' onclick = 'showList($i)'>{$i}</a> &nbsp;";
             }
     ?>
     </td>
 </tr>
 </table>

</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM