<script>
function loadCategory(cid) {
$.ajax({
url: "{:U('Product/list')}", // 統一入口
type: "GET", // 關鍵:分頁也是 GET,這裡必須一致
data: { cid: cid, page: 1 }, // 重置第 1 頁
dataType: "html",
beforeSend: function() {
$('#content').html('載入中...');
},
success: function(html) {
$('#content').html(html);
}
});
}
</script>
<script>
$(document).on('click', '#pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href'); // 取得分頁連結完整 URL (含 cid、page 參數)
$('#content').append('載入中...');
$('#content').load(url, function() {
$('#loading').remove();
// 重新綁定事件 (若內容含新分頁連結)
});
});
</script>
<?php
class ProductController extends Controller {
public function list() {
$cid = I('get.cid', 0, 'intval');
$page = I('get.page', 1, 'intval');
$pageSize = 20;
$where = ['status' => 1];
if ($cid > 0) $where['cid'] = $cid;
$count = M('Product')->where($where)->count();
$Page = new \Think\Page($count, $pageSize);
$Page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
// 關鍵:分頁連結必須保留 cid 參數
$Page->parameter = "cid=$cid";
$list = M('Product')
->where($where)
->order('sort desc, id desc')
->limit($Page->firstRow . ',' . $Page->listRows)
->select();
$this->assign('list', $list);
$this->assign('page', $Page->show());
// AJAX 請求回傳片段,非 AJAX 回傳完整頁面
if (IS_AJAX) {
$this->display('Product:ajax_list'); // 只含列表+分頁的模板
} else {
$this->display(); // 完整頁面含選單
}
}
}
?>
| 場景 | 選單請求 | 分頁連結 | 結果 |
|---|---|---|---|
| 錯誤 | POST (data: {cid:1}) | GET (`?cid=1&page=2`) | 後端 `$_GET['cid']` 取不到值,分頁失效 |
| 正確 | GET (`?cid=1`) | GET (`?cid=1&page=2`) | 參數一致,分頁正常 |
| 正確 | POST (data: {cid:1, page:1}) | POST (表單提交) | 需 JS 攔截分頁改為 POST 提交表單 |
<script>
// 使用 jQuery Pjax 自動處理 AJAX + pushState
$(document).pjax('#category-menu a, #pagination a', '#content', {
fragment: '#content', // 只提取目標容器
timeout: 5000,
});
</script>
後端配合 `if (IS_AJAX) $this->display('ajax_list');` 即可,瀏覽器網址列同步更新,支援前進後退。