Ajax無刷新分頁(Access+JQuery+JSON)

 原理:首先創建服務器處理分頁頁面,要根據action參數來決定是返回數據總條數還是某頁的數據.

GetCommentData.ashx:

<%@ WebHandler Language="C#" Class="GetDataCount" %>

using System;
using System.Web;

public class GetDataCount : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        var request = context.Request;
        var response = context.Response;
        string action =request["action"];
        jiang_Db newdb = new jiang_Db();
        if (action=="commentDataCount")//返回數據總條數
        {
            response.Write(newdb.ExecSql_Value("select count(*) from [comment]"));
        }
        else if (action=="commentDataPage")//返回分頁數據
        {
            string page=request["page"];//頁碼
            string pagesize = request["pagesize"];//每頁顯示條數
            System.Data.OleDb.OleDbDataReader reader = newdb.Re_DataReader("select * from (select top " + pagesize + " * from (select top " + Convert.ToInt32(page) * Convert.ToInt32(pagesize) + " * from [comment] order by [id]) order by [id] desc) order by id");
            response.Write(JSONHelper.GetJSON(reader,"comment"));//JSON序列化數據,並返回
            newdb.Close();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}



 

這次用的是access數據庫,不支持row_number() over()函數,所以要用下面這條比較複雜的sql語句.例如我們有11條數據,每頁顯示5條數據,所以要分三頁,sql語句如下:

select * from 
(select top 5 * from (select top 10 * 
from [comment] order by [id]) order by [id] desc)
 order by id

這條語句的原理是,比如要取6-10條,則先取前10條,再倒過來取前5條.

這裏服務器如果返回數據如果是分頁數據的話不可能是單條數據,一般用xml或者JSON來序列化格式後返回,這裏使用自己寫的JSON函數來直接把DataReader裏的數據序列化並返回string,返回的結果如下格式:



JSONHelper類:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;

public sealed class JSONHelper
{
    /**/
    ///
    /// 獲取JSON字符串SqlDataReader
    ///
    /// 值
    /// 數據表名
    ///
    public static string GetJSON(SqlDataReader drValue, string strTableName)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        //sb.AppendLine("{");
        //sb.AppendLine(" " + strTableName + ":{");
        //sb.AppendLine(" records:[");
        sb.AppendLine("[");
        try
        {
            while (drValue.Read())
            {
                sb.Append(" {");
                for (int i = 0; i < drValue.FieldCount; i++)
                {
                    sb.AppendFormat("\"{0}\":\"{1}\",", drValue.GetName(i), drValue.GetValue(i));
                }
                sb.Remove(sb.ToString().LastIndexOf(','), 1);
                sb.AppendLine("},");
            }
            sb.Remove(sb.ToString().LastIndexOf(','), 1);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            drValue.Close();
        }
        sb.AppendLine(" ]");
        //sb.AppendLine(" }");
        //sb.AppendLine(" };");
        return sb.ToString();
    }
    public static string GetJSON(OleDbDataReader drValue, string strTableName)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        //sb.AppendLine("{");
        //sb.AppendLine(" " + strTableName + ":{");
        //sb.AppendLine(" records:[");
        sb.AppendLine("[");
        try
        {
            while (drValue.Read())
            {
                sb.Append(" {");
                for (int i = 0; i < drValue.FieldCount; i++)
                {
                    sb.AppendFormat("\"{0}\":\"{1}\",", drValue.GetName(i), drValue.GetValue(i));
                }
                sb.Remove(sb.ToString().LastIndexOf(','), 1);
                sb.AppendLine("},");
            }
            sb.Remove(sb.ToString().LastIndexOf(','), 1);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
           drValue.Close();
        }
        sb.AppendLine(" ]");
       // sb.AppendLine(" }");
       // sb.AppendLine(" };");
        return sb.ToString();
    }

}


 

服務器頁面算寫好了,下面寫客戶端頁面:

客戶端要做的事情很簡單,那就是發送一個帶參數的請求給服務器,然後接受服務器返回的數據並用JQery的parseJSON()函數解析,再填充到頁面即可.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        #ulPage li
        {
            list-style-type: none;
            float: left;
            padding:5px;
        }
    </style>

    <script src="../js/jquery-1.4.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(function() {
            var pagesize = 5; //每頁顯示條數
            $.post("GetCommentData.ashx", { "action": "commentDataCount" }, function(data, status) {
                if (status == "success") {
                    var datacount = parseInt(data); //數據總條數
                    var pagenum; //頁數
                    if (datacount % pagesize == 0) {
                        pagenum = datacount / pagesize;
                    }
                    else {
                        pagenum = datacount / pagesize + 1;
                    }
                    for (var i = 1; i <= pagenum; i++) {
                        var li = $("<li><a href=''>" + i + "</a></li>"); //添加li
                        $("#ulPage").append(li);
                        //////////添加分頁點擊事件///////
                        li.click(function(e) {
                        e.preventDefault(); //阻止跳轉
                        $("#sp1").text("數據總條數:" + datacount + ",每頁顯示" + pagesize + "條,當前第" + $(this).text() + "頁 ");

                            $.post("GetCommentData.ashx", { "action": "commentDataPage", "page": $(this).text(), "pagesize": pagesize }, function(data, status) {
                                if (status == "success") {
                                    $("#ulContent").empty(); //清空li
                                    var comments = $.parseJSON(data); //JSON序列化數據
                                    for (var i = 0; i < comments.length; i++) {
                                        var comment = comments[i];
                                        var li = $("<li>" + comment.name + "   " + comment.uptime + "  " + comment.content + "</li>");
                                        $("#ulContent").append(li); //分別添加到頁面上
                                    }
                                }
                            });
                        });
                        //////////添加分頁點擊事件///////
                    }
                }
            });
    

        });
        
    </script>

</head>
<body>
    <ul id="ulContent">
    </ul>
    <span id="sp1"></span><ul id="ulPage">
    </ul>
</body>
</html>


效果圖:

發佈了29 篇原創文章 · 獲贊 0 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章