本文章利用Ajax分页来简单讲述一下如何利用php与ajax实现数据无刷新分页功能,有需要的朋友可参考一下。
简单的mysql数据表结构,代码如下:
- CREATE TABLE messages
- (
- msg_id INT PRIMARY KEY AUTO_INCREMENT,
- message VARCHAR(150)
- );
JavaScript代码,这里是ajax前段利用jquery来处理,代码如下:
- <script type="text/javascript" src="http:
- ajax/libs/jquery/1.4.2/jquery.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function()
- {
- function loading_show()
- {
- $('#loading').html("<img src='images/loading.gif'/>").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);
- $('#container .pagination li.active').live('click',function(){
- var page = $(this).attr('p');
- loadData(page);
- });
- });
- </script>
load_data.php,这里是获取由ajax发送的数据然后经过php查询mysql返回信息,代码如下:
- <?php
- if($_POST['page'])
- {
- $page = $_POST['page'];
- $cur_page = $page;
- $page -= 1;
- $per_page = 15;
- $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']);
- $msg .= "<li><b>" . $row['msg_id'] . "</b> " . $htmlmsg . "</li>";
- }
- $msg = "<div class='data'><ul>" . $msg . "</ul></div>";
-
- $query_pag_num = "SELECT COUNT(*) AS count FROM messages";
- $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);
-
-
- }
- ?>
(责任编辑:admin) |