You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django分页切换页面时如何保留原URL查询参数?

解决方案

方法一:前端JavaScript处理

直接通过JS动态修改分页链接的href属性,把分页URL和当前页面的查询参数拼接起来,步骤如下:

  1. 给分页链接加一个唯一标识,方便JS定位:
<a id="next-page-link" class="page-link" href="{% url 'home-paginated' page_obj.next_page_number %}">Next</a>
  1. 调用你的GetParams函数,修改链接的href值:
// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
  const nextLink = document.getElementById('next-page-link');
  if (nextLink) {
    const currentParams = GetParams();
    nextLink.href += currentParams;
  }
});

// 保留你的GetParams函数
function GetParams(){
   const queryString = window.location.search;
   return queryString;
}

页面加载后,Next链接会自动带上当前的查询参数,点击后就能跳转到目标分页并保留参数。

方法二:后端模板直接拼接(Django场景)

如果是Django项目,直接在模板里获取当前查询参数即可,无需前端JS:

<a class="page-link" href="{% url 'home-paginated' page_obj.next_page_number %}{{ request.GET.urlencode }}">Next</a>

{{ request.GET.urlencode }}会自动把当前页面的查询参数(如?sorted=normal)拼接到分页URL后,效果和JS方法一致,且兼容性更好。


内容的提问来源于stack exchange,提问作者KermitHQ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:51:31