Hướng dẫn phân trang bằng Ajax

Hôm này mình xin hướng dẫn các bạn phân trang bằng Ajax. trong bài hướng dẫn này tôi tôi sẽ tạo một cái class phantrang.class.php kế thừa từ class sanpham.class.php.

Class sanpham.class.php thì mình đã làm ở bài viết Tìm kiếm bằng Ajax rồi các bạn có thể xem lại bài viết nhé .Mình chỉ thêm vào một số nhỏ thôi.

Demo:

Đầu tiên các bạn tạo các file giống như bố cục ở hình bên dưới. Sao khi các bạn đã tạo xong thì chúng ta bắt đầu copy các đoạn code sao cho đúng từng file nhé.

code file phantrang.class.php ở file này sẽ kế thừa từ file sanpham.class.php nhé

phantrang.class.php

<?php
//inlcude sanpham.class.php
include 'sanpham.class.php';

class Phantrang extends Sanpham
{

  //thuoc tinh
  public $start; //vị trí bắt đầu
  public $total; //tổng số sản phẩm
  public $limit = 3; //ở đây mình lấy 3 sản phẩm trên 1 trang
  public $next; //button next
  public $back; //button back
  public $page_current; //trang hien tai
  public $page; //lấy page bên file phantrang.php đưa vào
  public function __construct($page = NULL)
  {

    parent::__construct();

    if ($page != NULL)
    {

      $this->page = $page;

      $this->getPage(); //gọi hàm getPage
      
    }

  }

  public function getPage()
  {

    if ($this->page != 1)
    {

      $this->start = ($this->page - 1) * $this->limit;

      $this->page_current = $this->page;

    }

    else
    {

      $this->start = $this->page - 1;

      $this->page_current = $this->page;

    }

  }

  public function totalRow()
  {

    $sql = "select * from dienthoai";

    Sanpham::select($sql);

    if (Sanpham::select_count() > 0)
    {

      $this->total = ceil(Sanpham::select_count() / $this->limit);

      return $this->total;

    }

  }
  public function select_product()
  {

    $sql = "select * from dienthoai limit $this->start,$this->limit";

    //echo $sql;
    Sanpham::select($sql);

    $count = Sanpham::select_count();

    $str = "";

    while ($row = Sanpham::fetch_array_table())
    {

      $str .= "<div class=\"sp1\">";

      $str .= "<img src=\"public/images/" . $row['hinhdt'] . "\" width=\"196\" height=\"150\">";

      $str .= "<h1 style=\"font-size:16px\">" . $row['tendt'] . "</h1>";

      $str .= "</div>";

    }

    return $str;

  }

  public function nut_phantrang()
  {

    $link = "<ul class=\"phantrang\">";

    if ($this->page_current > 1)
    {

      $this->back = $this->page_current - 1;

      $link .= "<li page='$this->back'>back</li>";

    }

    for ($i = 1;$i <= $this->totalRow();$i++)
    {

      if ($i == $this->page_current)
      {

        $link .= "<li page='$i' class=\"active\">" . $i . "</li>";

      }

      else
      {

        $link .= "<li page='$i'>" . $i . "</li>";

      }

    }

    if ($this->page_current < $this->totalRow())
    {

      $this->next = $this->page_current + 1;

      $link .= "<li page='$this->next'>next</li>";

    }
    $link .= "</ul>"return $link;

  }
}
?>

code trang phantrang.php ở trang này sẽ nhận giá trị trừ ajax gửi qua. mà ajax gửi qua cái gì? khi chúng ta click chuột vào một nút phân trang thì ajax sẽ lấy giá trị số trang đó ví dụ như là:1,2,3... thì sẽ gửi qua bên file phantrang.php để

nó xử lý, sao khi nó xử lý xong sẽ trả về dữ liệu của cái số trang mà ta mới click chuột vào.

code phantrang.php

<?php

    include_once('class/phantrang.class.php');   //include file phantrang.class.php vào nhé
    if(isset($_GET['page'])){
        $page=$_GET['page'];   //lấy giá trị ajax gửi qua
        //echo $page;
        $phantrang = new Phantrang($page);   //tạo đối tượng phân trang
        $dulieu=$phantrang->select_product();    //lấy thông tin sản phẩ
        $link_parination=$phantrang->nut_phantrang();  //lấy các link phân trang
        echo $dulieu.$link_parination;
    }


?>

 

Tiếp theo chúng ta nói về ajax, Các bạn muốn sử dụng ajax thì các bạn phải incluce thư viên của nó vào các bạn có thể lên mạng tại về.

đoạn code xử lý phân trang bằng ajax

$(document).ready(function(){
       function load(){

               phantrang(1);

       }
       function phantrang(page){

                   $('.loading').html("<img src='public/images/loading.gif'/>").fadeIn('fast'); 

                   $.ajax({

                       type:"get",

                       url:"phantrang.php",

                       data:{page:page},

                       success:function(data){

                           $('.loading').fadeOut('fast');

                           $(".allproduct").html(data);

                           //alert(data);

                       }

                   });

       }

       load();
       $("ul.phantrang li").live("click",function(){

          var page=$(this).attr('page');

           phantrang(page);

       //    alert(page);

       });

});

 

trong đoạn code ajax trên đầu tiên chúng ta sẽ load trang mặc định là trang số 1 nên chúng ta gọi hàm load()

type:là kiểu gửi các bạn có thể dùng get,post

url: là link dẫn tới trang xử lý

data: là dữ liệu chúng ta gửi qua với biến là page các bạn có thể đặt tuy ý biến nào cũng được

success:function(data) là dữ liệu trang xử lý gửi dữ liệu đã xử lý xong về cho chúng ta

Đây là toạn bộ code của file sanpham.php

<!DOCTYPE html>
<html>
<head>
    <title>San pham</title>
    <script type="text/javascript" src="public/js/jquery.1.7.2.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
       function load(){

               phantrang(1);

       }
       function phantrang(page){

             $('.loading').html("<img src='public/images/loading.gif'/>").fadeIn('fast'); 

             $.ajax({

                 type:"get",

                 url:"phantrang.php",

                 data:{page:page},

                 success:function(data){

                     $('.loading').fadeOut('fast');

                     $(".allproduct").html(data);

                     //alert(data);

                 }

             });

       }

       load();
       $("ul.phantrang li").live("click",function(){

          var page=$(this).attr('page');

           phantrang(page);

       //    alert(page);

       });
    });

    </script>

    <style type="text/css">

        .wapper{width:650px;margin: 0px auto;}

        div.allproduct{width: 650px; text-align: center;}

        div.allproduct div{float: left;}

        div.loading{width: 650px;text-align: center;position: absolute;}

        div.allproduct div.sp1{width: 200px;border: 1px solid #ccc;height: 210px;padding: 5px 5px;}

        /*link phantrang*/

        ul{width: 650px;float: left;}

        ul li{float: left;width: 50px; height: 50px;padding: 2px;list-style: none;border: 1px solid #ccc;background: #000;color:red;line-height: 50px;}

        ul li.active{background: blue;}

        ul li:hover{cursor: pointer;}

    </style>

</head>
<body>

    <div class="wapper">
            <div class="loading"></div>
            <div class="allproduct">
            </div>
    </div>
</body>
</html>

Chúc các bạn xử lý thành công!

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)