php Ajax分页简单应用实例

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

简单的mysql数据表结构,代码如下:

  1. CREATE TABLE messages
  2. (
  3. msg_id INT PRIMARY KEY AUTO_INCREMENT,
  4. message VARCHAR(150)
  5. );

JavaScript代码,这里是ajax前段利用jquery来处理,代码如下:

  1. <script type="text/javascript" src="http://ajax.googleapis.com/
  2. ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  3. <script type="text/javascript">
  4. $(document).ready(function()
  5. {
  6. function loading_show()
  7. {
  8. $('#loading').html("<img src='images/loading.gif'/>").fadeIn('fast');
  9. }
  10. function loading_hide()
  11. {
  12. $('#loading').fadeOut();
  13. }
  14. function loadData(page)
  15. {
  16. loading_show();
  17. $.ajax
  18. ({
  19. type: "POST",
  20. url: "load_data.php",
  21. data: "page="+page,
  22. success: function(msg)
  23. {
  24. $("#container").ajaxComplete(function(event, request, settings)
  25. {
  26. loading_hide();
  27. $("#container").html(msg);
  28. });
  29. }
  30. });
  31. }
  32. loadData(1); // For first time page load default results
  33. $('#container .pagination li.active').live('click',function(){
  34. var page = $(this).attr('p');
  35. loadData(page);
  36. });
  37. });
  38. </script>

load_data.php,这里是获取由ajax发送的数据然后经过php查询mysql返回信息,代码如下:

  1. <?php
  2. if($_POST['page'])
  3. {
  4. $page = $_POST['page'];
  5. $cur_page = $page;
  6. $page -= 1;
  7. $per_page = 15; // Per page records
  8. $previous_btn = true;
  9. $next_btn = true;
  10. $first_btn = true;
  11. $last_btn = true;
  12. $start = $page * $per_page;
  13. include"db.php";
  14. $query_pag_data = "SELECT msg_id,message from messages LIMIT $start, $per_page";
  15. $result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
  16. $msg = "";
  17. while ($row = mysql_fetch_array($result_pag_data))
  18. {
  19. $htmlmsg=htmlentities($row['message']); //HTML entries filter
  20. $msg .= "<li><b>" . $row['msg_id'] . "</b> " . $htmlmsg . "</li>";
  21. }
  22. $msg = "<div class='data'><ul>" . $msg . "</ul></div>"; // Content for Data
  23. /* -----Total count--- */
  24. $query_pag_num = "SELECT COUNT(*) AS count FROM messages"; // Total records
  25. $result_pag_num = mysql_query($query_pag_num);
  26. $row = mysql_fetch_array($result_pag_num);
  27. $count = $row['count'];
  28. $no_of_paginations = ceil($count / $per_page);
  29. /* -----Calculating the starting and endign values for the loop----- */
  30. //Some Code. Available in download script
  31. }
  32. ?>