【问题标题】:When I click to the next page on pagination, 404 error run当我点击分页下一页时,404错误运行
【发布时间】:2015-02-04 18:21:29
【问题描述】:

我试图在 CodeIgniter 中进行分页,但我猜我做错了。

  • 分页链接显示在页面底部。 (好的)
  • 单击分页链接上的数字时,出现错误 (404)。 (这是我无法解决的问题)

我的代码如下。

博客模型

function posts($cat_id='')
{
    $config['base_url']     = 'http://example.com/blog';
    $config['total_rows']   = 3;
    $config['per_page']     = 1;
    $config['num_links']    = 20;

    $this->pagination->initialize($config);

    if($cat_id) $this->db->where('cat_id',$cat_id);
    $query = $this->db->get('posts', $config['per_page'], $this->uri->segment(3));
    return $query->result();
}

blog_view

<?php echo $this->pagination->create_links(); ?>

【问题讨论】:

  • CI 中的分页可能会变得很棘手。分页只是构建链接,您仍然必须自己正确构建限制和偏移。将精力集中在如何构建查询而不是分页上。
  • 好吧!我会专注于它。我将在互联网上寻找与您的建议相关的更多信息。也许这就是我作为jr所需要的。开发人员。
  • 我也不确定您的段 3 对于页码的位置是否正确。如果是/blog/posts/cat_id/1,则页码(您的偏移量)位于第 4 段。
  • 谢谢你!这个建议救了我。正如我所见,我发布的代码完全正确。因为我更改了 $config['base_url'] = 'example.com/blog/index'; 上的路线而且我改变了段的数量并且它起作用了。现在可以看到链接 example.com/blog/index/1

标签: codeigniter pagination codeigniter-2


【解决方案1】:

CI 中的分页可能会变得很棘手。 分页只是构建链接,您仍然需要为数据库查询正确构建limitoffset

您必须将页码从 URL 传递到您的函数中

function posts($cat_id='', $page = FALSE)
{
    $config['base_url']     = 'http://example.com/blog';
    $config['total_rows']   = 3;
    $config['per_page']     = 1;
    $config['num_links']    = 20;
    $config['uri_segment']  = 3; // <-  verify this one

    $this->pagination->initialize($config);

    // set the page to 1 if the page is missing from the URL
    $page   = ($page === FALSE ? 1 : $page); 

    // calculate the offset for the query
    $offset = ($page - 1 ) * $config['per_page'];

    if($cat_id) $this->db->where('cat_id',$cat_id);
    $query = $this->db->get('posts', $config['per_page'], $offset);
    return $query->result();
}

根据 cmets 进行编辑:

我也不确定您的段 3 对于页码的位置是否正确。如果是/blog/posts/cat_id/1,则页码(您的偏移量)位于第 4 段。

【讨论】:

  • 其实问题出在路线上。在您对细分市场提出第二条建议后,我发现了这一点。在我用函数名称(例如 blog/index/)更改了 base_url 之后,我还更改了段数,它工作了!真的很感谢你。我会留意你关于建筑的第一个建议。
  • @Bari,是的,如果不查看您的 URL 和路由就很难知道。我更新了我的答案,使其对其他人更有用。
  • 现在我会在发送我的问题之前提供更多详细信息。 :) 这是我的错。很抱歉。
猜你喜欢
  • 1970-01-01
  • 2021-06-27
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多