Codeigniter 应用程序:如何将分页显示为 JSON?

Codeigniter application: how can I display pagination as JSON?

我正在使用 Codeigniter 3.1.8.

开发 博客应用程序

目前,它的管理区与前端分离得很好。

在前端,我设法用 JSONS 替换了 "classic" Codeigniter 视图。 (显示 JSONS 和 "handled" 与 AngularJS)。

这是控制器中用于所有帖子的代码:

private function _initPagination($path, $totalRows, $query_string_segment = 'page') {
        //load and configure pagination 
        $this->load->library('pagination');
        $config['base_url'] = base_url($path);
        $config['query_string_segment'] = $query_string_segment; 
        $config['enable_query_strings'] =TRUE;
        $config['reuse_query_string'] =TRUE;
        $config['total_rows'] = $totalRows;
        $config['per_page'] = 12;
        if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
            $_GET[$config['query_string_segment']] = 1;
        }
        $this->pagination->initialize($config);

        $limit = $config['per_page'];
        $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;

        return ['limit' => $limit, 'offset' => $offset];
    }

    public function index() {

    //call initialization method
        $config = $this->_initPagination("/", $this->Posts_model->get_num_rows());

        $data = $this->Static_model->get_static_data();
        $data['pages'] = $this->Pages_model->get_pages();
        $data['categories'] = $this->Categories_model->get_categories();  

        //use limit and offset returned by _initPaginator method
        $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);

        // All posts
        $this->output->set_content_type('application/json')->set_output(json_encode($data,JSON_PRETTY_PRINT));
    }

我没能做到的(尽管折磨着我的大脑)是将帖子的 分页 也显示为 JSON。

帖子模型中:

public function get_posts($limit, $offset) {
    $this->db->select('posts.*,categories.name as post_category');
    $this->db->order_by('posts.id', 'DESC');
    $this->db->join('categories', 'posts.cat_id = categories.id', 'inner');
    $query = $this->db->get('posts', $limit, $offset);
    return $query->result();
}

我的分页视图:

<div class="pagination-container text-center">
    <?php echo $this->pagination->create_links(); ?>
</div>

更新: 我已将整个 application 推送到 Github。如果你愿意,你可以深入了解一下。要创建所有 MySQL 表,运行 安装控制器。 :)

我该怎么办?

您有两个选择:

通过 ajax 请求 create_links() 字符串并将其附加到您需要的页面。 (顺便说一句,你可以根据需要设置样式,return 它已经设置了样式

echo json_encode(['pagination' => $this->pagination->create_links()]);

或者您可以 return 您需要的所有信息并自行处理,您所需要的只是 current_page 您已经请求或通过 $this->uri->segment(3) 获取并且您需要的信息总页数 total_rows/per_page.

echo json_encode(['total_pages' => $config['total_rows']/$config['per_page'], 'current_page' => $this->uri->segment(3)]);

我希望这能让您了解 Codeigniter 如何生成分页。

请注意:这是参考 CI 4 文档版本 4.0.0 rc1 Link: https://codeigniter4.github.io/userguide/libraries/pagination.html?highlight=pagination

<?php $pager->setSurroundCount(2) ?>

<nav aria-label="Page navigation">
    <ul class="pagination">
    <?php if ($pager->hasPrevious()) : ?>
        <li>
            <a href="<?= $pager->getFirst() ?>" aria-label="First">
                <span aria-hidden="true">First</span>
            </a>
        </li>
        <li>
            <a href="<?= $pager->getPrevious() ?>" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
            </a>
        </li>
    <?php endif ?>

    <?php foreach ($pager->links() as $link) : ?>
        <li <?= $link['active'] ? 'class="active"' : '' ?>>
            <a href="<?= $link['uri'] ?>">
                <?= $link['title'] ?>
            </a>
        </li>
    <?php endforeach ?>

    <?php if ($pager->hasNext()) : ?>
        <li>
            <a href="<?= $pager->getNext() ?>" aria-label="Previous">
                <span aria-hidden="true">&raquo;</span>
            </a>
        </li>
        <li>
            <a href="<?= $pager->getLast() ?>" aria-label="Last">
                <span aria-hidden="true">Last</span>
            </a>
        </li>
    <?php endif ?>
    </ul>
</nav>

尝试将上面示例中用于分页的所有必需变量作为 json 数据从您的控制器发送到您的视图,并像上面的示例一样创建它。

祝你一切顺利。

如果有效请告诉我

private function _initPagination($path, $totalRows, $page_offset) {
        //load and configure pagination 
        $this->load->library('pagination');
        $config = $this->config->item('pagination');
        $config['base_url'] = $path;
        $config['total_rows'] = $totalRows;
        $this->pagination->initialize($config);

        $limit = RECORDS_PER_PAGE;
        $offset = $page_offset;

        return ['limit' => $limit, 'offset' => $offset];
    }

    public function index() {

    $page_offset = ($this->input->get('per_page')) ? $this->input->get('per_page') : 0;

    //call initialization method
        $config = $this->_initPagination(site_url('controller_name/index?'), $this->Posts_model->get_num_rows(), $page_offset);

        $data = $this->Static_model->get_static_data();
        $data['pages'] = $this->Pages_model->get_pages();
        $data['categories'] = $this->Categories_model->get_categories();  

        //use limit and offset returned by _initPaginator method
        $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);

        // All posts
  }

或者让它更简单

public function index() {

    $params['limit'] = RECORDS_PER_PAGE; 
    $params['offset'] = ($this->input->get('per_page')) ? $this->input->get('per_page') : 0;

    $this->load->library('pagination');
    $config = $this->config->item('pagination');
    $config['base_url'] = site_url('controller/index?');
    $config['total_rows'] = $this->Posts_model->get_num_rows();
    $this->pagination->initialize($config);

    $data = $this->Static_model->get_static_data();
    $data['pages'] = $this->Pages_model->get_pages();
    $data['categories'] = $this->Categories_model->get_categories();  

    //use limit and offset
    $data['posts'] = $this->Posts_model->get_posts($param['limit'],$param['offset']);

  }

尝试这样的事情:

在 application/libraries/MY_Pagination 中创建新的 class。php

<?php

class MY_Pagination extends CI_Pagination
{
    public function get_as_array()
    {
        return [
            'total_rows' => $this->total_rows,
            'per_page' => $this->per_page,
            'cur_page' => $this->cur_page,
        ];
    }
}

在您的控制器中使用:

public function index() {

    //call initialization method
    $config = $this->_initPagination("/", $this->Posts_model->get_num_rows());

    $data = $this->Static_model->get_static_data();

    //this is the line I added
    $data['pagination'] = $this->pagination->get_as_array();

    $data['pages'] = $this->Pages_model->get_pages();
    $data['categories'] = $this->Categories_model->get_categories();  

    //use limit and offset returned by _initPaginator method
    $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);

    // All posts
    $this->output->set_content_type('application/json')->set_output(json_encode($data,JSON_PRETTY_PRINT));
}

对于 Angular 可以使用 https://ng-bootstrap.github.io/#/components/pagination/overview