Ajax+Jquery+Json,ASP.NET分页,存储过程分页

来源:互联网 发布:西门子plc解密软件 编辑:程序博客网 时间:2024/05/20 16:09

新建TestAjax.aspx

后台代码:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;//using System.Data.SqlClient;//namespace AjaxTest.AjaxPage{    public partial class TestAjax : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            //获取每页要显示多少条记录            string strPageSize = Request.QueryString["pagesize"];            int pageSize;            if (strPageSize == null)            {                pageSize = 3;//如果没有获取到参数,则将pageSize默认显示3条记录            }            else            {                pageSize = Convert.ToInt32(strPageSize);//将获取到的参数转换为int型            }            //获取当前页数            string strPageIndex = Request.QueryString["pageindex"];            int pageIndex;            if (strPageIndex == null)            {                pageIndex = 1;//如果没有获取到参数,则将pageIndex默认显示第一页            }            else            {                pageIndex = Convert.ToInt32(strPageIndex);            }            //调用数据库中分页的存储过程            SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=MyBookShop;User ID=sa;password=123");            SqlCommand command = new SqlCommand("books_pager ", conn);//books_pager为分页的存储过程名            command.CommandType = CommandType.StoredProcedure;//更改CommandType的类型            conn.Open();//打开连接            //books_pager此存储过程需要3个参数,实例化3个参数对象            SqlParameter spPageSize = new SqlParameter("@pageSize", pageSize);//每页显示多少条记录            SqlParameter spPageIndex = new SqlParameter("@pageIndex", pageIndex);//当前页            SqlParameter spTotalPages = new SqlParameter("@totalPages", SqlDbType.Int);//总页数,SqlDbType.Int将数据类型转换为int型            spTotalPages.Direction =  ParameterDirection.Output;//总页数为输出参数            command.Parameters.Add(spPageSize);            command.Parameters.Add(spPageIndex);            command.Parameters.Add(spTotalPages);                        SqlDataReader reader = command.ExecuteReader();            string content = "";//要输出的内容            while (reader.Read())            {                int id = (int)reader["bookId"];                string title = reader["Title"].ToString();                string isbn = reader["ISBN"].ToString();                string unitPrice = reader["UnitPrice"].ToString();                //以json格式输出                content += "{\"id\":\"" + id + "\",\"title\":\"" + title + "\",\"isbn\":\"" + isbn +"\",\"unitPrice\":\"" + unitPrice + "\"},";            }            string subContent = content.Substring(0,content.Length-1);//将json格式的内容最后一个逗号截掉            conn.Close();//关闭连接            int totalPages = (int)spTotalPages.Value; ;//总页数【注意:需要在数据库关闭连接之后才能获取到总页数,否则会出错】            //以json格式输出            Response.Write("{");            Response.Write("\"name\":\"Books\",");            Response.Write("\"totalpages\":\"" + totalPages + "\",");            Response.Write("\"records\":");            Response.Write("[");            Response.Write(subContent);            Response.Write("]");            Response.Write("}");            Response.End();//停止输出        }    }}

新建TestAjax.htm

前台页面代码:

<!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>Ajax+Jquery+json分页</title>    <style type="text/css">        table{ border:1px solid black; border-collapse:collapse;}        table th{ border:1px solid black;}        table tr td{ border:1px solid black;}    </style>    <script src="../js/jquery-1.6.2.min.js" type="text/javascript"></script>    <script type="text/javascript" language="javascript">        var pageIndex = 1;//默认显示第一页        var totalPages; //总页数        $(function () {            $.ajax({                url: "TestAjax.aspx", //发送请求的URL地址.                 dataType: "json", //服务器返回的数据类型                //每页显示3条记录,当前页是第一页,[要发送给服务器的数据,以 Key/value 的键值对形式表示,会做为QueryString附加到请求URL中]                data: { pagesize: 10, pageindex: pageIndex },                success: function (data, textStatus) {//[返回的data可以是xmlDoc,jsonObj,html,text等][textStatus请求状态:success,error等]                    for (var i = 0; i < data.records.length; i++) {//循环输出内容                        $("<tr><td>" + data.records[i].title + "</td><td>" + data.records[i].isbn + "</td><td>" + data.records[i].unitPrice + "</td><td>" + data.records[i].id + "</td></tr>").appendTo($("table"));                    }                    totalPages = window.parseInt(data.totalpages); //获取总页数                    $("#ShotTotalPage").text("共" + totalPages + "页" + "/" + "第" + pageIndex + "页");                },                error: function (XMLHttpRequest, textStatus, errorThrown) {//XMLHttpRequest对象,错误信息,可能)捕获的错误对象                    // 通常情况下textStatus和errorThown只有其中一个有值                     alert("error:" + errorThrown); //弹出错误消息                }            });            //下一页            $("[value=下一页]").click(function () {                pageIndex++;                if (pageIndex >= totalPages) {                    pageIndex = totalPages;                    $(this).attr("disabled", true);                }                else {                    $(this).attr("disabled", false);                }                if (pageIndex <= 1) {                    pageIndex = 1;                    $("[value=上一页]").attr("disabled", true);                }                else {                    $("[value=上一页]").attr("disabled", false);                }                                $.ajax({                    url: "TestAjax.aspx", //发送请求的URL地址.                     dataType: "json", //服务器返回的数据类型                    //每页显示3条记录,当前页是第一页,[要发送给服务器的数据,以 Key/value 的键值对形式表示,会做为QueryString附加到请求URL中]                    data: { pagesize: 10, pageindex: pageIndex },                    success: function (data, textStatus) {//[返回的data可以是xmlDoc,jsonObj,html,text等][textStatus请求状态:success,error等]                        $("table tr:gt(0)").remove();                        for (var i = 0; i < data.records.length; i++) {//循环输出内容                            $("<tr><td>" + data.records[i].title + "</td><td>" + data.records[i].isbn + "</td><td>" + data.records[i].unitPrice + "</td><td>" + data.records[i].id + "</td></tr>").appendTo($("table"));                        }                        totalPages = window.parseInt(data.totalpages); //获取总页数                        $("#ShotTotalPage").text("共" + totalPages + "页" + "/" + "第" + pageIndex + "页");                    },                    error: function (XMLHttpRequest, textStatus, errorThrown) {//XMLHttpRequest对象,错误信息,可能)捕获的错误对象                        // 通常情况下textStatus和errorThown只有其中一个有值                         alert("error:" + errorThrown); //弹出错误消息                    }                });            });                       //上一页            $("[value=上一页]").click(function () {                pageIndex--;                if (pageIndex >= totalPages) {                    pageIndex = totalPages;                    $(this).attr("disabled", true);                }                else {                    $(this).attr("disabled", false);                }                if (pageIndex <= 1) {                    pageIndex = 1;                    $("[value=上一页]").attr("disabled", true);                }                else {                    $("[value=上一页]").attr("disabled", false);                }                $.ajax({                    url: "TestAjax.aspx", //发送请求的URL地址.                     dataType: "json", //服务器返回的数据类型                    //每页显示3条记录,当前页是第一页,[要发送给服务器的数据,以 Key/value 的键值对形式表示,会做为QueryString附加到请求URL中]                    data: { pagesize: 10, pageindex: pageIndex },                    success: function (data, textStatus) {//[返回的data可以是xmlDoc,jsonObj,html,text等][textStatus请求状态:success,error等]                        $("table tr:gt(0)").remove();                        for (var i = 0; i < data.records.length; i++) {//循环输出内容                            $("<tr><td>" + data.records[i].title + "</td><td>" + data.records[i].isbn + "</td><td>" + data.records[i].unitPrice + "</td><td>" + data.records[i].id + "</td></tr>").appendTo($("table"));                        }                        totalPages = window.parseInt(data.totalpages); //获取总页数                        $("#ShotTotalPage").text("共" + totalPages + "页" + "/" + "第" + pageIndex + "页");                    },                    error: function (XMLHttpRequest, textStatus, errorThrown) {//XMLHttpRequest 对象,错误信息,(可能)捕获的错误对象                        // 通常情况下textStatus和errorThown只有其中一个有值                         alert("error:" + errorThrown); //弹出错误消息                    }                });            });        });    </script></head><body><div>    <table>        <tr>            <th>书名</th><th>ISBN</th><th>价格</th><th>编号</th>        </tr>    </table>    <p>        <input type="button" disabled="disabled" value="上一页" />        <input type="button"  value="下一页" />        <label id="ShotTotalPage"></label>    </p></div></body></html>

分页存储过程见另一篇文章


原创粉丝点击