通过Ajax实现无刷新分页

出处:http://www.cnblogs.com/minioutman/archive/2013/01/31/2887051.html

效果描述:分页点击下一页、上一页时,不刷新整个页面,只更新列表数据。

•原理说明:

(1) 通过JS把页面上的数据转化成 JSON 数据( JavaScript Object Notation, 是一种轻量级的数据交换格式)

 1 <script type="text/javascript">
 2         var PageSize = 5;
 3         var AllRecordCount = 0;
 4
 5         function PageSelectCallback(page_id, jq) {
 6             InitData(page_id);
 7         }
 8
 9         function InitData(pageindx) {
10             $.ajax({
11                 type: "POST",
12                 dataType: "json",
13                 url: "StudyHistoryPager.ashx",  //调用ashx文件,指定路径
14                 data: "PageIndex=" + (pageindx + 1) + "&PageSize=" + PageSize + "&KnowledgeID=" + ‘<%=KnowledgeID %>‘,//通过传入ashx文件的参数
15
16                 complete: function () {
17                     $("#FAQList").fadeIn("slow");
18                     $("#Pagination").show();
19                     $("#divload").hide();
20                 },
21           //json是从ashx文件返回的数据
22                 success: function (json) {
23                     var tbody = "<table cellspacing=‘0‘ cellpadding=‘2‘ border=‘0‘ width=‘100%‘>";
24                     $("#FAQList").empty();
25                     for (var key in json) {
26                         if (key == "0") {
27                             AllRecordCount = json[key].AllRecordCount;
28                         }
29                         var trs = "<tr><td align=‘left‘ width=‘70%‘ style=‘border-bottom: #ccc 1px dashed;‘><img src=‘../Skin/Img/studyhistory.png‘ />&nbsp;&nbsp;" + json[key].CreateTimeString + "&nbsp;&nbsp;<span class=‘red‘>" + json[key].UserName + "</span>学习了该文章。</td></tr>";
30                         tbody += trs;
31
32                     }
33                     tbody += "</table>";
34
35                     if (AllRecordCount < 1) {
36                         $("#FAQList").append("<div class=‘ac‘>很抱歉,暂时没有学习记录。</div>");
37                     }
38                     else {
39                         $("#FAQList").append(tbody);
40                         $("#Pagination").show().pagination(AllRecordCount, {
41                             callback: PageSelectCallback,
42                             prev_text: ‘上一页‘,
43                             next_text: ‘下一页‘,
44                             items_per_page: PageSize,
45                             num_display_entries: 5,
46                             current_page: pageindx,
47                             num_edge_entries: 2
48                         });
49                     }
50                 }
51             });
52         }
53         window.onload = function () {
54             InitData(0);
55         }
56     </script>

(2) 同时把这些数据传到一个“一般处理程序(.ashx)”

public void ProcessRequest(HttpContext context)
        {
            //不让浏览器缓存
            context.Response.Buffer = true;
            context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";
            context.Response.ContentType = "text/plain";

            int pageIndex;
            int.TryParse(context.Request["PageIndex"], out pageIndex);

            int pageSize;
            int.TryParse(context.Request["PageSize"], out pageSize);

            string knowledgeID = context.Request["KnowledgeID"];

            #region 查询逻辑       //设置查询参数
            Hashtable searchHashTable = new Hashtable();
            Utility.CreateSearchCondition("t1.KnowledgeID", UtilityFunction.InputText(knowledgeID), "=", SqlDbType.UniqueIdentifier, "KnowledgeID", "KnowledgeID", ref searchHashTable);
            PageInfo pageInfo = new PageInfo();
            pageInfo.PageIndex = pageIndex;
            pageInfo.PageSize = pageSize;
            pageInfo.OrderField = "CreateTime DESC ";
            searchHashTable.Add("PageInfo", pageInfo);

            //查询合同信息
            StudyHistoryBLL studyHistoryBll = new StudyHistoryBLL();
            DataSet ds = studyHistoryBll.GetList(searchHashTable);

            if (ds.Tables[1].Rows.Count == 0 && pageIndex > 1)
            {
                pageInfo.PageIndex = pageIndex - 1;
                ds = studyHistoryBll.GetList(searchHashTable);
            }
            DataTable dt = ds.Tables[1];
            DataColumn column = new DataColumn();
            column.DataType = Type.GetType("System.String");
            column.ColumnName = "CreateTimeString";
            dt.Columns.Add(column);
            DataColumn column2 = new DataColumn();
            column2.DataType = Type.GetType("System.Int32");
            column2.ColumnName = "AllRecordCount";
            dt.Columns.Add(column2);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["CreateTimeString"] = dt.Rows[i]["CreateTime"].ToString();
                dt.Rows[i]["AllRecordCount"] = ds.Tables[0].Rows[0][0];
            }       #endregion 
            string jsonData = JsonUtility.DataTableToJson(dt);

            context.Response.Write(jsonData);
        }

/// <summary>

    /// 将DataTable转换为JSON 

    /// </summary>

    /// <param name="dtb">Dt</param>

    /// <returns>JSON字符串</returns>

    public static string DataTableToJson(DataTable dt)

    {

        JavaScriptSerializer jss = new JavaScriptSerializer();

        System.Collections.ArrayList dic = new System.Collections.ArrayList();

        foreach (DataRow dr in dt.Rows)

        {

            Dictionary<string, object> drow = new Dictionary<string, object>();

            foreach (DataColumn dc in dt.Columns)

            {

                drow.Add(dc.ColumnName, dr[dc.ColumnName]);

            }

            dic.Add(drow);

        }

        //序列化 

        return jss.Serialize(dic);

    }

(3)在ashx文件中查询数据,然后将查询结果返回到页面。

(4)在页面中接收到返回的查询结果后进行分页。

效果如下:

原创,转载请说明出处。

时间: 2024-08-10 00:07:29

通过Ajax实现无刷新分页的相关文章

Ajax实现无刷新分页

注:本文中使用到的一些类库在前面文章都能找到源代码,我会在文中指明链接所在,为了缩短文章篇幅,由此带来的阅读不便,敬请谅解. 本文讲解 Ajax 实现无刷新分页.实现原理.代码展示.代码下载. 这里需要说明一些知识: 1.Ajax 无刷新页面的好处:提供良好的客户体验,通过 Ajax 在后台从数据库中取得数据并展示,取缔了等待加载页面而出现的空白状态: 2.那么,Ajax 无刷新页面是运行在动态页面(.PHP)?还是静态页面(.html/.htm/.shtml)?答案是:静态页面: 3.实现原理

Ajax 实现无刷新分页

Ajax 实现无刷新分页

smarty+php+ajax 简单无刷新分页

简介 分页,无非就是从数据库中获得我们想查询的数据,再加以处理即可! ① 确定数据总数($count) ② 每页显示数据条数($pageSize) ③ 分多少页($pageCount) ④ 上一页($pagePrev) ⑤ 下一页($pageNext) ⑥ 判断越界问题 ⑦ 偏移量($offset) ⑧ sql语句($sql = "select * from goods limit $offset,$pageSize";) 简单归简单,我们还得考虑实际的应用.例如:如果你正在土豆网看&

在Thinkphp中使用AJAX实现无刷新分页

在Thinkphp目录的Lib\ORG\Util\目录里新建AjaxPage.class.php,写入一下内容: <?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------

jQuery+AJAX+Struts实现无刷新分页

jQuery+AJAX+Struts实现无刷新分页 说明: 1.需要jQuery插件js文件: 2.使用myeclipse添加struts能力: 从前从客户端页面向服务器发送Ajax请求,需要在js中先创建XMLHttpRequest对象,对象创建好以后使用OPEN('GET/POST',URL,同步/异步)设置提交方式,URL地址,使用同步还是异步方式.然后使用send(data)向服务器发送数据,同时使用onreadystatechange来绑定回调函数.如果是使用GET方式提交数据,那么就

Bootstrap Paginator分页插件+ajax 实现动态无刷新分页

之前做分页想过做淘宝的那个,但是因为是后台要求不高,就Bootstrap Paginator插件感觉还蛮容易上手,所以就选了它. Bootstrap Paginator分页插件下载地址: DownloadVisit Project in GitHub 1.这是需要分页的页面放的 js函数: [javascript] view plaincopy <span style="font-size:14px;">function paging(page){ $.ajax({ typ

Ajax无刷新分页

<!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> <sc

asp.net练习②——Paginaton无刷新分页

aspx代码: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>无刷新分页</title> <link href="c

无刷新分页 jquery.pagination.js

1.使用插件为 jquery.pagination.js ,如果没有这个js文件的话,我可以给发个. 首先引用 jquery.pagination.js (分页js),跟pagination.css(分页样式css). 点击获取查看这两个文件 2.页面js代码为 <script type="text/javascript"> var pageIndex = 0; //页面索引初始值 var pageSize = 15; //每页显示条数初始化,修改显示条数,修改这里即可 $