Home  >  Article  >  php教程  >  php Ajax分页简单应用实例

php Ajax分页简单应用实例

WBOY
WBOYOriginal
2016-06-13 09:47:411166browse

本文章利用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

    }
    ?>

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn