萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP + AJAX 無刷新分頁技術實作完整指南

傳統分頁每次換頁都需重新載入整個頁面,體驗較差。結合 PHP 後端輸出片段 HTML 與 前端 AJAX 非同步請求,可實現無刷新分頁,大幅提升使用者體驗。本文提供完整的前後端程式碼與架構說明。

系統架構

  • sn_inq.php:主查詢頁,包含搜尋表單、分頁容器、AJAX 引擎
  • sn_show.php:後端資料處理,接收查詢條件與頁碼,輸出純 HTML 片段(表格列+分頁導航)

前端核心:AJAX 引擎與表單序列化

<script>
// 通用表單序列化:將所有輸入控制項轉為 query string
function getFormValue(form) {
    var str = '';
    for (var i = 0; i < form.elements.length; i++) {
        var el = form.elements[i];
        var type = el.type.toLowerCase();
        var name = el.name;
        if (!name) continue;

        switch (type) {
            case 'select-one':
            case 'text':
            case 'password':
            case 'hidden':
            case 'textarea':
                str += name + '=' + encodeURIComponent(el.value) + '&';
                break;
            case 'radio':
            case 'checkbox':
                if (el.checked) str += name + '=' + encodeURIComponent(el.value) + '&';
                break;
        }
    }
    return str.replace(/&$/, '');
}

// 顯示指定頁面資料
function showPage(page) {
    showLoading('show'); // 顯示載入中
    var params = getFormValue(document.form1);
    var url = 'sn_show.php?page=' + page + '&' + params;

    fetch(url)
        .then(r => r.text())
        .then(html => {
            document.getElementById('show').innerHTML = html;
            hideLoading('show');
        })
        .catch(err => {
            console.error(err);
            hideLoading('show');
            alert('載入失敗,請重試');
        });
}

// 載入指示器
function showLoading(containerId) {
    var el = document.getElementById(containerId);
    el.innerHTML = '<div class="loading"><img src="spinner.gif"> 載入中...</div>';
}
function hideLoading(containerId) {
    var el = document.getElementById(containerId);
    var loader = el.querySelector('.loading');
    if (loader) loader.remove();
}

// 頁面載入時預設顯示第 1 頁
window.onload = function() { showPage(1); };
</script>

主頁面結構 (sn_inq.php)

<form name="form1" method="post">
  <!-- 搜尋條件 -->
  <input type="text" name="keyword" placeholder="關鍵字">
  <select name="status">
    <option value="">全部狀態</option>
    <option value="1">啟用</option>
    <option value="0">停用</option>
  </select>
  <button type="button" onclick="showPage(1)">查詢</button>
</form>

<!-- 資料顯示區(AJAX 會替換此處內容) -->
<div id="show"></div>

後端資料輸出 (sn_show.php)

<?php
require 'db_config.php';
$page   = max(1, intval($_GET['page']));
$limit  = 20;
$offset = ($page - 1) * $limit;

// 動態建構 WHERE 條件
$where = ['1=1'];
$params = [];
$types = '';

if (!empty($_GET['keyword'])) {
    $where[] = '(sn_id LIKE ? OR sn_plant LIKE ? OR sn_sales LIKE ?)';
    $kw = '%' . $_GET['keyword'] . '%';
    $params = array_merge($params, [$kw, $kw, $kw]);
    $types .= 'sss';
}
if (isset($_GET['status']) && $_GET['status'] !== '') {
    $where[] = 'sn_sts = ?';
    $params[] = $_GET['status'];
    $types .= 'i';
}

$sqlCount = 'SELECT COUNT(*) FROM sn WHERE ' . implode(' AND ', $where);
$stmt = $mysqli->prepare($sqlCount);
if ($params) $stmt->bind_param($types, ...$params);
$stmt->execute();
$stmt->bind_result($total);
$stmt->fetch();
$stmt->close();

$totalPages = ceil($total / $limit);

// 查詢資料
$sql = 'SELECT sn_id, sn_plant, sn_sales, sn_act, sn_type, sn_sts, date_created
        FROM sn WHERE ' . implode(' AND ', $where) .
        ' ORDER BY date_created DESC LIMIT ?, ?';
$params[] = $offset;
$params[] = $limit;
$types .= 'ii';

$stmt = $mysqli->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
?>
<table class="data-table">
  <thead>
    <tr><th>ID</th><th>廠區</th><th>業務</th><th>活動</th><th>類型</th><th>狀態</th><th>建立時間</th></tr>
  </thead>
  <tbody>
<?php while ($row = $result->fetch_assoc()): ?>
    <tr>
        <td><?= htmlspecialchars($row['sn_id']) ?></td>
        <td><?= htmlspecialchars($row['sn_plant']) ?></td>
        <td><?= htmlspecialchars($row['sn_sales']) ?></td>
        <td><?= htmlspecialchars($row['sn_act']) ?></td>
        <td><?= htmlspecialchars($row['sn_type']) ?></td>
        <td><?= $row['sn_sts'] ? '啟用' : '停用' ?></td>
        <td><?= $row['date_created'] ?></td>
    </tr>
<?php endwhile; ?>
  </tbody>
</table>

<!-- 分頁導航 -->
<div class="pagination">
<?php
// 產生頁碼連結,onclick 呼叫前端 showPage()
$range = 2; // 顯示當前頁前後各 2 頁
$start = max(1, $page - $range);
$end   = min($totalPages, $page + $range);

if ($page > 1) {
    echo '<a href="javascript:void(0)" onclick="showPage(' . ($page-1) . ')">« 上一頁</a> ';
}
if ($start > 1) echo '<a onclick="showPage(1)">1</a> ... ';

for ($i = $start; $i <= $end; $i++) {
    $cls = ($i == $page) ? ' class="current"' : '';
    echo '<a' . $cls . ' href="javascript:void(0)" onclick="showPage(' . $i . ')">' . $i . '</a> ';
}

if ($end < $totalPages) echo '... <a onclick="showPage(' . $totalPages . ')">' . $totalPages . '</a> ';
if ($page < $totalPages) {
    echo '<a href="javascript:void(0)" onclick="showPage(' . ($page+1) . ')">下一頁 »</a>';
}
echo '<span class="info">共 ' . $total . ' 筆 / ' . $totalPages . ' 頁</span>';
?>
</div>

進階優化方向

  • History API:使用 history.pushState() 更新 URL,支援瀏覽器前進後退、書籤分享
  • 防抖動:搜尋輸入時延遲 300ms 再送出,避免頻繁請求
  • 快取機制:前端以 Map 快取已載入頁面,重複點擊無需再請求
  • 錯誤重試:網路失敗時自動重試 2 次,並顯示友善提示
  • 無限捲動:捲動至底部自動載入下一頁,替代傳統分頁導航
copyright © 萬盛學電腦網 all rights reserved