Codeigniter 3中使用Jquery的Ajax分页

Codeigniter 3中使用Jquery的Ajax分页

在这一部分中,我们将学习在Codeigniter 3中使用Ajax分页。我们将使用JQuery来实现这个功能。每个网站开发者都希望通过使用JQuery Ajax的代码来构建网站,因为它能够节省时间并忽略额外的加载时间。如果我们不使用JQuery Ajax,每次需要加载整个页面。当我们在网站上使用JQuery Ajax时,它只会加载数据,而不是整个页面。

要执行Ajax分页,我们需要按照一些步骤进行操作。首先,我们需要创建一个名为”Post”的表。然后,我们将使用该表添加一些虚拟记录。然后,我们将使用Ajax分页来展示所有的数据。要完成这个步骤,具体如下所述:

步骤1:

在这一步中,我们将 创建Posts表 。首先,我们会创建一个名为”posts”的表,之后,我们会向表中添加一些虚拟记录,具体如下所述:

posts table
CREATE TABLE IF NOT EXISTS `posts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `slug` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=533 ;

步骤2:

在这一步中,我们将进行 数据库配置 。为此,我们将添加一些关于数据库的信息,例如数据库名、用户名和密码,具体如下所述:

application/config/database.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

active_group = 'default';query_builder = TRUE;

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => 'root',
    'database' => 'test',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

步骤3:

在这一步中,我们要 创建一个帖子控制器 。该控制器将使用loadRecord()和index()方法创建。我们将使用loadRecord()方法来获取ajax数据。视图由index方法返回。现在我们将使用控制器文件夹并像这样创建一个新的方法:

application/controllers/Post.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Post extends CI_Controller {

    /**
     * This method returns all the data.
     *
     * @return Response
    */
    public function __construct(){
       parent::__construct();
       this->load->helper('url');this->load->library('pagination');
       this->load->database();
    }

    /**
     * This method returns all the data.
     *
     * @return Response
    */
    public function index(){this->load->view('post_view');
    }

    /**
     * This method returns all the data.
     *
     * @return Response
    */
    public function loadRecord(rowno=0){rowperpage = 5;

        if(rowno != 0){rowno = (rowno-1) *rowperpage;
        }

        allcount =this->db->count_all('posts');

        this->db->limit(rowperpage, rowno);users_record = this->db->get('posts')->result_array();config['base_url'] = base_url().'post/loadRecord';
        config['use_page_numbers'] = TRUE;config['total_rows'] = allcount;config['per_page'] = rowperpage;config['full_tag_open']    = '<div class="pagging text-center"><nav><ul class="pagination">';
        config['full_tag_close']   = '</ul></nav></div>';config['num_tag_open']     = '<li class="page-item"><span class="page-link">';
        config['num_tag_close']    = '</span></li>';config['cur_tag_open']     = '<li class="page-item active"><span class="page-link">';
        config['cur_tag_close']    = '<span class="sr-only">(current)</span></span></li>';config['next_tag_open']    = '<li class="page-item"><span class="page-link">';
        config['next_tag_close']  = '<span aria-hidden="true"></span></span></li>';config['prev_tag_open']    = '<li class="page-item"><span class="page-link">';
        config['prev_tag_close']  = '</span></li>';config['first_tag_open']   = '<li class="page-item"><span class="page-link">';
        config['first_tag_close'] = '</span></li>';config['last_tag_open']    = '<li class="page-item"><span class="page-link">';
        config['last_tag_close']  = '</span></li>';this->pagination->initialize(config);data['pagination'] = this->pagination->create_links();data['result'] = users_record;data['row'] = rowno;

        echo json_encode(data);
  }

}

步骤4:

在这一步中,我们将 创建视图文件 。我们将使用我们的 views 文件夹,并创建一个名为 “post_view.php” 的新视图文件。我们将把以下代码添加到该文件中:

application/views/post_view.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <title> JQuery - Codeigniter 3 Ajax Pagination </title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
    <style type="text/css">
      html, body { font-family: 'Raleway', sans-serif; }
      a{ color: #007bff; font-weight: bold;}
    </style>
  </head> 
  <body>

   <div class="container">
    <div class="card">
      <div class="card-header">
        Codeigniter Ajax Pagination using JQuery 
      </div>
      <div class="card-body">
           <!-- Posts List -->
           <table class="table table-borderd" id='postsList'>
             <thead>
              <tr>
                <th>S.no</th>
                <th>Title</th>
              </tr>
             </thead>
             <tbody></tbody>
           </table>

           <!-- Paginate -->
           <div id='pagination'></div>
      </div>
    </div>
   </div>

   <!-- Script -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script type='text/javascript'>
   (document).ready(function(){('#pagination').on('click','a',function(e){
       e.preventDefault(); 
       var pageno = (this).attr('data-ci-pagination-page');
       loadPagination(pageno);
     });

     loadPagination(0);

     function loadPagination(pagno){.ajax({
         url: '/post/loadRecord/'+pagno,
         type: 'get',
         dataType: 'json',
         success: function(response){
            ('#pagination').html(response.pagination);
            createTable(response.result,response.row);
         }
       });
     }

     function createTable(result,sno){
       sno = Number(sno);('#postsList tbody').empty();
       for(index in result){
          var id = result[index].id;
          var title = result[index].title;
          var content = result[index].slug;
          content = content.substr(0, 60) + " ...";
          var link = result[index].slug;
          sno+=1;

          var tr = "<tr>";
          tr += "<td>"+ sno +"</td>";
          tr += "<td><a href='"+ link +"' target='_blank' >"+ title +"</a></td>";
          tr += "</tr>";
          $('#postsList tbody').append(tr);

        }
      }

    });
    </script>
  </body>
</html>

现在我们的上述代码已经准备好了,我们可以运行它。当我们运行这段代码时,将生成以下输出:

Codeigniter 3中使用Jquery的Ajax分页

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程