首頁  >  文章  >  php教程  >  php Ajax分页简单应用实例

php Ajax分页简单应用实例

WBOY
WBOY原創
2016-06-13 09:47:411201瀏覽

本文章利用Ajax分页来简单讲述一下如何利用php与ajax实现数据无刷新分页功能,有需要的朋友可参考一下。

简单的mysql数据表结构

 代码如下 复制代码

CREATE TABLE messages
(
msg_id INT PRIMARY KEY AUTO_INCREMENT,
message VARCHAR(150)
);

JavaScript 代码

这里是ajax前段利用jquery来处理

 代码如下 复制代码


function loading_show()
{
$('#loading').html("php Ajax分页简单应用实例").fadeIn('fast');
}

function loading_hide()
{
$('#loading').fadeOut();
}

function loadData(page)
{
loading_show();
$.ajax
({
type: "POST",
url: "load_data.php",
data: "page="+page,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
});

load_data.php

这里是获取由ajax发送的数据然后经过php查询mysql返回信息

 代码如下 复制代码

if($_POST['page'])
{
$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 15; // Per page records
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
include"db.php";
$query_pag_data = "SELECT msg_id,message from messages LIMIT $start, $per_page";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result_pag_data))
{
$htmlmsg=htmlentities($row['message']); //HTML entries filter
$msg .= "

  • " . $row['msg_id'] . " " . $htmlmsg . "
  • ";
    }
    $msg = "
      " . $msg . "
    "; // Content for Data
    /* -----Total count--- */
    $query_pag_num = "SELECT COUNT(*) AS count FROM messages"; // Total records
    $result_pag_num = mysql_query($query_pag_num);
    $row = mysql_fetch_array($result_pag_num);
    $count = $row['count'];
    $no_of_paginations = ceil($count / $per_page);
    /* -----Calculating the starting and endign values for the loop----- */

    //Some Code. Available in download script

    }
    ?>

    陳述:
    本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn