1. 程式人生 > >ASP.NET+Ajax+JQuey+Json資料+儲存過程實現無重新整理分頁

ASP.NET+Ajax+JQuey+Json資料+儲存過程實現無重新整理分頁

<!--引入jquery-1.6.2-->
<!--ShowPageData1.aspx頁面-->
<script src="../Jquery/jquery-1.6.2.min.js" type="text/javascript"></script>

<!--引入jquery-1.6.2-->
    <script type="text/javascript" language="javascript">
    var pageIndex=1; //當前頁碼
    var totalPage; //總頁數
    $(function () {
        $.ajax({
            url: "GetPageDataBySql.aspx", //請求頁面
            dataType: "json",         //返回的資料型別為json
            data: { pagesize: 3, pageindex: pageIndex }, //向url那個頁面傳兩個引數
            success: function (getdata, stext) {
                for (var i = 0; i < getdata.records.length; i++) {
                    $("<tr><td>" + getdata.records[i].isbn + "</td><td>" + getdata.records[i].id + "</td><td>" + getdata.records[i].unitprice + "</td><td>" + getdata.records[i].title + "</td></tr>").appendTo($("table"));
                    totalPage = window.parseInt(getdata.totalpage);
                }
            },
            error: function (xmlhttprequest, st, e) {
                alert("Error:" + e); //列印錯誤訊息
            }
        });

        //下一頁
        $("[value=下一頁]").click(function () {
            pageIndex++;
            if (pageIndex >= totalPage) {
                pageIndex = totalPage;    //如果當前頁碼大於等於總頁數,當前頁碼就等於總頁數
                $(this).attr("disabled", true); //下一頁不可點選(this代表當前點選的按鈕)
            } else {
                $(this).attr("disabled", false); //否則下一頁可點選(this代表當前點選的按鈕)
            }

            if (pageIndex <= 1) {
                pageIndex = 1; //如果當前頁碼小於等於1,則當前頁碼為第一頁
                $("[value=上一頁]").attr("disabled", true); //上一頁不可點選
            } else {
                $("[value=上一頁]").attr("disabled", false); //上一頁可點選
            }
             //重新繫結資料
            $.ajax({
                url: "GetPageDataBySql.aspx",   //請求頁面
                dataType: "json",       //返回的資料型別為json
                data: { pagesize: 3, pageindex: pageIndex },  //向url那個頁面傳兩個引數
                success: function (getdata, stext) {
                    //每次點選下一頁的時候都要清空當前頁的資料
                    $("table tr:gt(0)").remove();
                    for (var i = 0; i < getdata.records.length; i++) {
                        $("<tr><td>" + getdata.records[i].isbn + "</td><td>" + getdata.records[i].id + "</td><td>" + getdata.records[i].unitprice + "</td><td>" + getdata.records[i].title + "</td></tr>").appendTo($("table"));
                        totalPage = window.parseInt(getdata.totalpage);
                    }
                },
                error: function (xmlhttprequest, st, e) {
                    alert("Error:" + e); //列印錯誤訊息
                }
            });
        });

        //上一頁
        $("[value=上一頁]").click(function () {
            pageIndex--;
            if (pageIndex >= totalPage) {
                pageIndex = totalPage;    //如果當前頁碼大於等於總頁數,當前頁碼就等於總頁數
                $(this).attr("disabled", true); //下一頁不可點選(this代表當前點選的按鈕)
            } else {
                $(this).attr("disabled", false); //否則下一頁可點選(this代表當前點選的按鈕)
            }

            if (pageIndex <= 1) {
                pageIndex = 1; //如果當前頁碼小於等於1,則當前頁碼為第一頁
                $("[value=上一頁]").attr("disabled", true); //上一頁不可點選
            } else {
                $("[value=上一頁]").attr("disabled", false); //上一頁可點選
            }
            //重新繫結資料
            $.ajax({
                url: "GetPageDataBySql.aspx",    //請求頁面
                dataType: "json",    //返回的資料型別為json
                data: { pagesize: 3, pageindex: pageIndex }, //向url那個頁面傳兩個引數
                success: function (getdata, stext) {
                    //每次點選上一頁的時候都要清空當前頁的資料
                    $("table tr:gt(0)").remove();
                    for (var i = 0; i < getdata.records.length; i++) {
                        $("<tr><td>" + getdata.records[i].isbn + "</td><td>" + getdata.records[i].id + "</td><td>" + getdata.records[i].unitprice + "</td><td>" + getdata.records[i].title + "</td></tr>").appendTo($("table"));
                        totalPage = window.parseInt(getdata.totalpage);
                    }
                },
                error: function (xmlhttprequest, st, e) {
                    alert("Error:" + e); //列印錯誤訊息
                }
            });
        });

    });
    </script>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <th>封面</th>
                <th>編號</th>
                <th>價格</th>
                <th>標題</th>
            </tr>
        </table>
        <p>
            <input type="button" value="上一頁" disabled="disabled" />
            <input type="button" value="下一頁"  />
        </p>
    </div>
    </form>
</body>


//GetPageDataBySql.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class UseJqueryPage1_GetPageDataBySql : 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); //如果不為空的話就直接拿到就ok
        }
        string strPageIndex = Request.QueryString["pageindex"];//當前頁碼
        int pageIndex;
        if (strPageIndex == null)
        {
            pageIndex = 1; //如果客戶端傳過來的那個pageindex為空的話,就預設當前是第一頁
        }
        else {
            pageIndex = Convert.ToInt32(strPageIndex); //如果不為空的話就直接拿到pageindex就ok
        }
        //呼叫資料庫中的儲存過程進行分頁
        SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=MyBookShop;Integrated Security=True"); //這裡是連線資料庫的連線串
        SqlCommand command = new SqlCommand("books_pager", conn); //執行儲存過程 books_pager表示資料庫儲存過程的名字
        command.CommandType = System.Data.CommandType.StoredProcedure;//呼叫儲存過程必須設定commandType為執行儲存
        //儲存過程需要3個引數,所以必須例項化3個引數物件
        SqlParameter pPageSize = new SqlParameter("@pageSize",pageSize);
        SqlParameter pPageIndex = new SqlParameter("@pageIndex",pageIndex);
        SqlParameter pTotalPages = new SqlParameter("@totalPages",System.Data.SqlDbType.Int); //總頁數是要輸出的
        pTotalPages.Direction = System.Data.ParameterDirection.Output;//輸出引數

        //增加引數
        command.Parameters.Add(pPageIndex);
        command.Parameters.Add(pPageSize);
        command.Parameters.Add(pTotalPages);
        conn.Open(); //開啟資料庫連結

        SqlDataReader reader = command.ExecuteReader();//執行查詢
        string content = "";
        while (reader.Read()) {
            int bookId = (int)reader["bookId"];
            string title = reader["Title"].ToString();
            string isbn = reader["ISBN"].ToString();
            string price = reader["UnitPrice"].ToString();
            content += "{\"id\":\""+bookId+"\",\"isbn\":\""+isbn+"\",\"title\":\""+title+"\",\"unitprice\":\""+price+"\"},";
        }
        string subContent = content.Substring(0,content.Length-1); //擷取json最後面的那個逗號,因為content正常輸出的時候最後面多了一個逗號

        conn.Close(); //關閉資料庫連線
        int totalPage = (int)pTotalPages.Value; //必須要資料庫關閉之後才可以獲取輸出的引數(即是總頁數)
        Response.Write("{");
        Response.Write("\"name\":\"Books\",");
        Response.Write("\"totalPage\":\""+totalPage+"\",");
        Response.Write("\"records\":");
        Response.Write("[");
        Response.Write(subContent);
        Response.Write("]");
        Response.Write("}");

        Response.End();
    }
}


--資料庫儲存過程
create proc books_pager
	@pageSize int,--每頁顯示多少行
	@pageIndex int,--當前的頁數
	@totalPages int output--總頁數
as
declare @startIndex int
declare @endIndex int
declare @totalRows int
select @totalRows=COUNT(*) from Books
set @totalPages = @totalRows/@pageSize
if(@totalRows%@pageSize!=0)
begin
	set @[email protected]+1
end
set @startIndex=(@pageIndex-1)*@pageSize+1
set @endIndex = @startIndex + @pageSize-1
declare @booktemp table([id] int identity(1,1) not null,bookId int)
insert @booktemp
select Id from Books
select * from @booktemp as t,Books as b
where t.bookId=b.Id and t.id>[email protected] and t.id<[email protected]
go