Ajax無重新整理分頁(Access+JQuery+JSON)

來源:互聯網
上載者:User

 原理:首先建立伺服器處理分頁頁面,要根據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>

:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.