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

JavaScript如何实现点击按钮时在API请求URL中传递动态页码

修改后的HTML代码

<table class="table">
  <thead class="tablehead">
    <tr class="tablerow">
        <th>Sno</th>
        <th>Company</th>
        <th>Title</th>
        <th>Created At</th>
        <th>Expiration Date</th>
        <th>Is Expired</th>
        <th>Job_link</th>
        <th>location</th>
    </tr>
  </thead>
  <tbody id="JobList" class="tableBody"></tbody>
</table>
<!-- 新增分页控制区域 -->
<div style="margin: 16px 0;">
  <button id="prevBtn">上一页</button>
  <span style="margin: 0 12px;">当前页:<span id="pageNum">1</span></span>
  <button id="nextBtn">下一页</button>
</div>

修改后的JS代码

// 把页码抽离为全局变量,方便修改
let currentPage = 1
// 接口基础地址抽离
const BASE_URL = '/api/job/list?'
// 获取DOM元素缓存,避免重复查询
const jobListDom = document.querySelector('#JobList')
const prevBtn = document.querySelector('#prevBtn')
const nextBtn = document.querySelector('#nextBtn')
const pageNumDom = document.querySelector('#pageNum')

// 分页请求函数,支持传入指定页码
function fetchData(page = currentPage) {
    // 每次请求前先清空旧列表数据
    jobListDom.innerHTML = ''
    // 拼接请求地址,修正多余的&符号
    fetch(`${BASE_URL}page=${page}`)
    .then(response =>{
        if(!response.ok){
            throw Error('请求出错')
        }
        return response.json(); 
    })
    .then(data => {
        // 更新当前页码变量和显示
        currentPage = page
        pageNumDom.innerText = currentPage
        // 按钮边界禁用逻辑:第一页禁用上一页
        prevBtn.disabled = currentPage <= 1

        // --- 可选扩展:如果接口返回总页数/总条数,可以加上下一页的边界判断 ---
        // 示例:假设接口返回 totalPage 字段代表总页数
        // nextBtn.disabled = currentPage >= data.totalPage

        // 渲染列表:去掉重复的tbody标签,仅返回tr内容
        const html = data.job_list.map(user => {
            return `
            <tr>
              <td>${user.sno}</td>
              <td>${user.company}</td>
              <td>${user.title}</td>
              <td>${user.created_at}</td>
              <td>${user.expiration_date}</td>
              <td>${user.is_expired}</td>
              <td>
                  <a href="${user.job_link}">
                      <div style="
                          white-space: nowrap; 
                          overflow: hidden;
                          text-overflow: ellipsis"
                      >
                          ${user.job_link}
                      </div>
                  </a>
              </td>
              <td>${user.location}</td>
            </tr>                                
            `
        }).join("");
        jobListDom.insertAdjacentHTML('afterbegin' , html);
    })
    .catch(error => {
        console.log(error)
    });
}

// 绑定上一页点击事件
prevBtn.addEventListener('click', () => {
    if (currentPage > 1) {
        fetchData(currentPage - 1)
    }
})

// 绑定下一页点击事件
nextBtn.addEventListener('click', () => {
    // 如果有总页数判断,在这里加逻辑:currentPage < 总页数 才允许翻页
    fetchData(currentPage + 1)
})

// 初始化加载第一页数据
fetchData();

关键修改说明

  • 页码变量从请求函数内部抽离为全局可修改的状态,支持翻页时动态变更
  • 新增分页按钮和对应的点击事件,实现页码的增减逻辑
  • 修复原有渲染逻辑的问题:删除了重复生成的tbody标签,翻页前先清空旧列表数据,避免内容叠加
  • 新增页码边界判断,防止请求小于1的无效页码
  • 可以根据接口返回的总页数字段,扩展下一页的最大页码限制,避免请求超出范围的页码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:27:02