欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net中利用Jquery+Ajax+Json实现无刷新分页的实例代码

程序员文章站 2024-02-27 15:23:21
复制代码 代码如下:<%@ page language="c#" autoeventwireup="true" codefile="ajaxjson.aspx.cs"...

复制代码 代码如下:

<%@ page language="c#" autoeventwireup="true" codefile="ajaxjson.aspx.cs" inherits="ajaxjson" %>
<!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>jquery+ajax+json分页</title>
    <meta http-equiv="content-type" content="text/html; charset=gb2312">
    <link href="styles/tablecloth.css" rel="stylesheet" type="text/css" />
    <link href="styles/pagination.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript" src="scripts/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="scripts/jquery.pagination.js"></script>
    <script type="text/javascript">
    var pageindex = 0;     //页面索引初始值
    var pagesize = 10;     //每页显示条数初始化,修改显示条数,修改这里即可
    $(function () {
        inittable(0);    //load事件,初始化表格数据,页面索引为0(第一页)  
        //分页,pagecount是总条目数,这是必选参数,其它参数都是可选
        $("#pagination").pagination(<%=pagecount %>, {
            callback: pagecallback,
            prev_text: '上一页',       //上一页按钮里text
            next_text: '下一页',       //下一页按钮里text
            items_per_page: pagesize,  //显示条数
            num_display_entries: 6,    //连续分页主体部分分页条目数
            current_page: pageindex,   //当前页索引
            num_edge_entries: 2        //两侧首尾分页条目数
        });

        //翻页调用
        function pagecallback(index, jq) {
            inittable(index);
        }

        //请求数据
        function inittable(pageindex) {
            $.ajax({
                type: "post",
                datatype: "json",
                url: 'supplyajax.aspx',      //提交到一般处理程序请求数据
                data: "type=show&random=" + math.random() + "&pageindex=" + (pageindex + 1) + "&pagesize=" + pagesize, //提交两个参数:pageindex(页面索引),pagesize(显示条数)   
                error: function () { alert('error data'); },  //错误执行方法 
                success: function (data) {
                    $("#result tr:gt(0)").remove();        //移除id为result的表格里的行,从第二行开始(这里根据页面布局不同页变)
                    var json = data; //数组
                    var html = "";
                    $.each(json.data, function (index, item) {
                        //循环获取数据 
                        var id = item.id;
                        var name = item.name;
                        var sex = item.sex;
                        html += "<tr><td>" + id + "</td><td>" + name + "</td><td>" + sex + "</td></tr>";
                    });
                    $("#result").append(html);             //将返回的数据追加到表格
                }
            });
        }
    });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <table id="result" cellspacing="0" cellpadding="0">
        <tr>
            <th>
                编号
            </th>
            <th>
                姓名
            </th>
            <th>
                性别
            </th>
        </tr>
    </table>
    <div id="pagination">
    </div>
    </form>
</body>
</html>


复制代码 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.text;
using system.net;
using system.io;
using system.web.ui;
using system.web.ui.webcontrols;

public partial class ajaxjson : system.web.ui.page
{
    public string pagecount = string.empty; //总条目数

    protected void page_load(object sender, eventargs e)
    {
        if (!ispostback)
        {
            string url = "/supplyajax.aspx";
            string strresult = getrequestjsonstring(url, "type=getcount");
            pagecount = strresult.tostring();
        }
    }

    #region 后台获取ashx返回的数据
    /// <summary>
    /// 后台获取ashx返回的数据
    /// </summary>
    /// <param name="relativepath">地址</param>
    /// <param name="data">参数</param>
    /// <returns></returns>
    public static string getrequestjsonstring(string relativepath, string data)
    {
        string requesturl = getrequesturl(relativepath, data);

        try
        {
            webrequest request = webrequest.create(requesturl);
            request.method = "get";

            streamreader jsonstream = new streamreader(request.getresponse().getresponsestream());
            string jsonobject = jsonstream.readtoend();

            return jsonobject;
        }
        catch
        {
            return string.empty;
        }
    }

    public static string getrequesturl(string relativepath, string data)
    {
        string absolutepath = httpcontext.current.request.url.absoluteuri;
        string hostnameandport = httpcontext.current.request.url.authority;
        string applicationdir = httpcontext.current.request.applicationpath;
        stringbuilder sbrequesturl = new stringbuilder();
        sbrequesturl.append(absolutepath.substring(0, absolutepath.indexof(hostnameandport)));
        sbrequesturl.append(hostnameandport);
        sbrequesturl.append(applicationdir);
        sbrequesturl.append(relativepath);
        if (!string.isnullorempty(data))
        {
            sbrequesturl.append("?");
            sbrequesturl.append(data);
        }
        return sbrequesturl.tostring();
    }
    #endregion
}


复制代码 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.data;
using system.web.ui;
using system.web.ui.webcontrols;
//新增  
using system.web.script.serialization;
using system.text;


public partial class supplyajax : system.web.ui.page
{
    protected static list<student> studentlist = new list<student>();
    protected static int recordcount = 0;
    protected static datatable dt = createdt();
    protected void page_load(object sender, eventargs e)
    {
        switch (request["type"])
        {
            case "show":
                #region 分页配置
                //具体的页面数
                int pageindex;
                int.tryparse(request["pageindex"], out pageindex);
                //页面显示条数
                int pagesize = convert.toint32(request["pagesize"]);
                if (pageindex == 0)
                {
                    pageindex = 1;
                }
                #endregion
                datatable pageddt = getpagedtable(dt, pageindex, pagesize);
                list<student> list = new list<student>();
                foreach (datarow dr in pageddt.rows)
                {
                    student c = new student();
                    c.id = (int32)dr["id"];
                    c.name = dr["name"].tostring();
                    c.sex = dr["sex"].tostring();
                    list.add(c); 
                }
                string json = new javascriptserializer().serialize(list);//这个很关键,否则error
                stringbuilder builder = new stringbuilder();
                builder.append("{");
                builder.append("\"recordcount\":" + recordcount + ",");
                builder.append("\"data\":");
                builder.append(json);
                builder.append("}");
                response.contenttype = "application/json";
                response.write(builder.tostring());
                break;
            case "getcount":
                response.write(dt.rows.count);
                break;
            case "add":
                break;
            case "update":
                break;
            case "delete":
                break;
        }
        response.end();
    }

    #region 模拟数据
    private static datatable createdt()
    {
        datatable dt = new datatable();
        dt.columns.add(new datacolumn("id", typeof(int)) { defaultvalue = 0 });
        dt.columns.add(new datacolumn("name", typeof(string)) { defaultvalue = "1" });
        dt.columns.add(new datacolumn("sex", typeof(string)) { defaultvalue = "男" });
        for (int i = 1; i <= 1000; i++)
        {
            dt.rows.add(i, "张三" + i.tostring().padleft(4, '0'));
        }
        recordcount = dt.rows.count;
        return dt;
    }
    #endregion

    /// <summary> 
    /// 对datatable进行分页,起始页为1 
    /// </summary> 
    /// <param name="dt"></param> 
    /// <param name="pageindex"></param> 
    /// <param name="pagesize"></param> 
    /// <returns></returns> 
    public static datatable getpagedtable(datatable dt, int pageindex, int pagesize) 
    { 
        if (pageindex == 0) 
            return dt; 
        datatable newdt = dt.copy(); 
        newdt.clear();   
        int rowbegin = (pageindex - 1) * pagesize; 
        int rowend = pageindex * pagesize; 
        if (rowbegin >= dt.rows.count) 
            return newdt; 
        if (rowend > dt.rows.count) 
            rowend = dt.rows.count; 
        for (int i = rowbegin; i <= rowend - 1; i++) 
        { 
            datarow newdr = newdt.newrow(); 
            datarow dr = dt.rows[i]; 
            foreach (datacolumn column in dt.columns) 
            { 
                newdr[column.columnname] = dr[column.columnname]; 
            } 
            newdt.rows.add(newdr); 
        } 
        return newdt; 
    } 

    /// <summary> 
    /// 获取总页数 
    /// </summary> 
    /// <param name="sumcount">结果集数量</param> 
    /// <param name="pagesize">页面数量</param> 
    /// <returns></returns> 
    public static int getpagecount(int sumcount, int pagesize) 
    { 
        int page = sumcount / pagesize; 
        if (sumcount % pagesize > 0) 
        { 
            page = page + 1; 
        } 
        return page; 
    } 
 

    public struct student
    {
        public int id;
        public string name;
        public string sex;
    } 
}