Ajax+Ashx 无刷新分页

前端之家收集整理的这篇文章主要介绍了Ajax+Ashx 无刷新分页前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

提高用户体验,使用无刷新分页,异步加载数据,实现主要用到:

1.序号主要用ROW_NUMBER()函数

2.后台获取数据页面为ashx

先看下效果图:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NoAltas.aspx.cs" Inherits="Pages_Cu_CuExam_NoAltas" %>
<!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 runat="server">
<title>无刷新分页例子</title>
<script src="/Jquery/jquery-1.4.4.min.js" type="text/javascript"></script>
<style type="text/css">
         body
         {  FONT:16px/28px 微软雅黑 }
        .hidden
        {display: none; }
        span{color:Red;}
         .btnCss
        {
          margin-left:5px;
          padding:2px; 
          background:#81c560;
          cursor:pointer;
          font-size:12px;
          color:#fff;
        }
        input { width:50px; border:1px solid #ddd}
        table { border:1px solid #ccc; width:1002px}
 </style>
<script type="text/javascript">
    $(document).ready(function () {
        Init();
        $("#preview").click(function () {
            var pageIndex = $("#pageIndex").text();
            if (pageIndex <= 1) {
                return false;
            }
            $('#next').attr('disabled','');
            var newIndex = parseInt(pageIndex) - 1;
            $("#pageIndex").text(newIndex);
            $.get("Page.ashx",{ pageIndex: newIndex },function (data) {
                $("#showContent").empty().append(data);
            });
            return false;
        });
        $("#next").click(function () {
            var pageIndex = $("#pageIndex").text();
            var count = $("#lblCount").text();
            if (pageIndex >= parseInt(count)) {
                $('#next').attr('disabled','disabled');
                return false;
            }
            var newIndex = parseInt(pageIndex) + 1;
            $("#pageIndex").text(newIndex);
            $.get("Page.ashx",function (data) {
                $("#showContent").empty().append(data);
            });
            return false;
        });
        $("#go").click(function () {
            var pageIndex = $("#pageNum").val();
            $("#pageIndex").text(pageIndex)
            var count = $("#lblCount").text();
            if (pageIndex > parseInt(count)) {
                alert("超过页数了");
                return false;
            }
            $.get("Page.ashx",{ pageIndex: pageIndex },function (data) {
                $("#showContent").empty().append(data);
            });
            return false;
        });
    });
    function Init() {
        $.get("Page.ashx",{ pageIndex: 1 },function (data) {
            $("#showContent").empty().append(data);
            var count = $("#lblCount").text();
            $("#pageCount").text(count + "");
        })
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="showContent"></div>
    <div id="pageTool">共<span id="pageCount"></span>页 当前第<span id="pageIndex">1</span>页
       <span id="preview" class="btnCss" >上一页</span><span id="next" class="btnCss">下一页</span>
       跳转: <input type ="text" id="pageNum"  onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"/> <span id="go" class="btnCss">确定</span>
    </div>
    </form>
</body>

</html>

<%@ WebHandler Language="C#" Class="Page" %>
using System;
using System.Web;
using System.Text;
using System.Data;
//author:洪生鹏
//date :2012-08-16
public class Page : IHttpHandler {
    int pageCount = 0;
    int pageRowCount = 10;
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        int pageIndex = Convert.ToInt32(context.Request["pageIndex"]);
        pageCount = this.GetPageCount();
        string page = "<label class='hidden' id='lblCount'>" + pageCount + "</label>";
        string result = "";
        if (pageIndex == 1)
        {
            result = PageInit();
            context.Response.Write(result + page);
        }
        else
        {
            result = GetPageIndex(pageIndex);
            context.Response.Write(result + page);
        }
    }
    /// <summary>
    ///  初始化页面 加载页面数据
    /// </summary>
    /// <returns></returns>
    public string PageInit()
    {
        try
        {
            string sql = "SELECT TOP  10 * FROM  TestTable (NOLOCK)";
            BaseBLL<BaseModel> bll = new BaseBLL<BaseModel>();
            DataTable dt = bll.GetDataTable(sql);
            return OutPutTable(dt);
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
    public string GetPageIndex(int pageIndex)
    {
        try
        {
            if (pageCount < pageIndex || pageIndex <= 0)
            {
                return "";
            }
            else if (pageIndex == 1)
            {
                return PageInit();
            }
            else
            {
                int topRow = pageIndex * pageRowCount;
                string sql = string.Format(@"SELECT  * FROM (SELECT *,ROW_NUMBER() OVER (ORDER BY Id) AS rn
                FROM TestTable f) t WHERE  t .rn > {1} AND t .rn <= {0}",topRow,topRow - pageRowCount);
                BaseBLL<BaseModel> bll = new BaseBLL<BaseModel>();
                DataTable dt = bll.GetDataTable(sql);
                return OutPutTable(dt);
            }
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    private int GetPageCount()
    {
        string sql = "SELECT COUNT(ID) FROM TestTable f";
        double pageC = 0;
        BaseBLL<BaseModel> bll = new BaseBLL<BaseModel>();
        DataTable dt = bll.GetDataTable(sql);
        if (dt != null && dt.Rows.Count > 0)
        {
            double count = Convert.ToDouble(dt.Rows[0][0]);
            pageC = Math.Ceiling(count / Convert.ToDouble(pageRowCount));
        }
        return (int)pageC;
    }
    /// <summary>
    /// 输出一个Table 
    /// </summary>
    /// <param name="dt">数据集</param>
    /// <returns></returns>
    private string OutPutTable(DataTable dt)
    {
        StringBuilder sb = new StringBuilder("");
        sb.Append("<table>");
        sb.Append("<tr><td>序号</td><td>姓名</td><td>编号</td><td>职业</td></tr>");
        if (dt != null && dt.Rows.Count >0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string ID = dt.Rows[i]["ID"].ToString();
                string name = dt.Rows[i]["EmployeeName"].ToString();
                string workNo = dt.Rows[i]["WorkNo"].ToString();
                string profession = dt.Rows[i]["Profession"].ToString();
                string temp = string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>",ID,name,workNo,profession);
                sb.Append(temp);
            }
        }
        sb.Append("</table>");
        return sb.ToString();
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

猜你在找的Ajax相关文章