基於 Jquery+Ajax+Json高效分頁實現代碼

來源:互聯網
上載者:User

 

 代碼如下 複製代碼
<%@ WebHandler Language="C#" Class="GetData" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class GetData : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
var pageIndex = context.Request["PageIndex"];
string connectionString = @"Data Source=KUSESQLEXPRESS;Initial Catalog=bookshop;Integrated Security=True";
//判斷當前索引存不存在,如果不存在則擷取記錄的總數。
if (string.IsNullOrEmpty(pageIndex))
{
//擷取查詢記錄總數的sql語句
string sql = "select count(-1) from books";
int count = 0;
int.TryParse(SqlHelper.ExecuteScalar(connectionString, System.Data.CommandType.Text, sql, null).ToString(), out count);
context.Response.Write(count);
context.Response.End();
}
//當根據索引擷取資料
else
{
int currentPageIndex = 1;
int.TryParse(pageIndex, out currentPageIndex);
SqlParameter[] parms = new SqlParameter[] {
new SqlParameter("@FEILDS",SqlDbType.NVarChar,1000),
new SqlParameter("@PAGE_INDEX",SqlDbType.Int,10),
new SqlParameter("@PAGE_SIZE",SqlDbType.Int,10),
new SqlParameter("@ORDERTYPE",SqlDbType.Int,2),
new SqlParameter("@ANDWHERE",SqlDbType.VarChar,1000),
new SqlParameter("@ORDERFEILD",SqlDbType.VarChar,100)
};
parms[0].Value = "*";//擷取所有的欄位
parms[1].Value = pageIndex;//當前頁面索引
parms[2].Value = 10;//頁面大小
parms[3].Value = 0;//升序排列
parms[4].Value = "";//條件陳述式
parms[5].Value = "ID";//排序欄位
List<Book> list = new List<Book>();
using (SqlDataReader sdr = SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, "PAGINATION", parms))
{
while (sdr.Read())
{
list.Add(new Book { Title = sdr[2].ToString(), Auhor = sdr[2].ToString(), PublishDate = sdr[4].ToString(), ISBN = sdr[5].ToString() });
}
}
context.Response.Write(new JavaScriptSerializer().Serialize(list).ToString());//轉為Json格式
}
}
public bool IsReusable {
get {
return false;
}
}
}
public class Book
{
public string Title { get; set; }
public string Auhor { get; set; }
public string PublishDate { get; set; }
public string ISBN { get; set; }
}

  

顯示頁面

 

 代碼如下 複製代碼
<body>
<div >
<table id="content">/*顯示資料內容*/
</table>
<div id="pager" class="yahoo2"></div>/*顯示分頁條*/
</div>
</body>

js代碼

 

 代碼如下 複製代碼
$(function () {
$.post("GetData.ashx", null, function (data) {
var total = data;
PageClick(1, total, 3);
});
PageClick = function (pageIndex, total, spanInterval) {
$.ajax({
url: "GetData.ashx",
data: { "PageIndex": pageIndex },
type: "post",
dataType: "json",
success: function (data) {
//索引從1開始
//將當前頁索引轉為int類型
var intPageIndex = parseInt(pageIndex);
//擷取顯示資料的表格
var table = $("#content");
//清楚表格中內容
$("#content tr").remove();
//向表格中新增內容
for (var i = 0; i < data.length; i++) {
table.append(
$("<tr><td>" +
data[i].Title
+ "</td><td>" +
data[i].Auhor
+ "</td><td>" +
data[i].PublishDate
+ "</td><td>" +
data[i].ISBN
+ "</td></tr>")
);
} //for
//建立分頁
//將總記錄數結果 得到 總頁碼數
var pageS = total
if (pageS % 10 == 0) pageS = pageS / 10;
else pageS = parseInt(total / 10) + 1;
var $pager = $("#pager");
//清楚分頁div中的內容
$("#pager span").remove();
$("#pager a").remove();
//添加第一頁
if (intPageIndex == 1)
$pager.append("<span class='disabled'>第一頁</span>");
else {
var first = $("<a href='javascript:void(0)' first='" + 1 + "'>第一頁</a>").click(function () {
PageClick($(this).attr('first'), total, spanInterval);
return false;
});
$pager.append(first);
}
//添加上一頁
if (intPageIndex == 1)
$pager.append("<span class='disabled'>上一頁</span>");
else {
var pre = $("<a href='javascript:void(0)' pre='" + (intPageIndex - 1) + "'>上一頁</a>").click(function () {
PageClick($(this).attr('pre'), total, spanInterval);
return false;
});
$pager.append(pre);
}
//設定分頁的格式 這裡可以根據需求完成自己想要的結果
var interval = parseInt(spanInterval); //設定間隔
var start = Math.max(1, intPageIndex - interval); //設定起始頁
var end = Math.min(intPageIndex + interval, pageS)//設定末頁
if (intPageIndex < interval + 1) {
end = (2 * interval + 1) > pageS ? pageS : (2 * interval + 1);
}
if ((intPageIndex + interval) > pageS) {
start = (pageS - 2 * interval) < 1 ? 1 : (pageS - 2 * interval);
}
//產生頁碼
for (var j = start; j < end + 1; j++) {
if (j == intPageIndex) {
var spanSelectd = $("<span class='current'>" + j + "</span>");
$pager.append(spanSelectd);
} //if
else {
var a = $("<a href='javascript:void(0)'>" + j + "</a>").click(function () {
PageClick($(this).text(), total, spanInterval);
return false;
});
$pager.append(a);
} //else
} //for
//上一頁
if (intPageIndex == total) {
$pager.append("<span class='disabled'>下一頁</span>");
}
else {
var next = $("<a href='javascript:void(0)' next='" + (intPageIndex + 1) + "'>下一頁</a>").click(function () {
PageClick($(this).attr("next"), total, spanInterval);
return false;
});
$pager.append(next);
}
//最後一頁
if (intPageIndex == pageS) {
$pager.append("<span class='disabled'>最後一頁</span>");
}
else {
var last = $("<a href='javascript:void(0)' last='" + pageS + "'>最後一頁</a>").click(function () {
PageClick($(this).attr("last"), total, spanInterval);
return false;
});
$pager.append(last);
}
} //sucess
}); //ajax
}; //function
}); //ready

sql語句

 

 代碼如下 複製代碼
CREATE PROCEDURE [dbo].[PAGINATION]
@FEILDS VARCHAR(1000),--要顯示的欄位
@PAGE_INDEX INT,--當前頁碼
@PAGE_SIZE INT,--頁面大小
@ORDERTYPE BIT,--當為0時 則為 desc 當為1 時 asc
@ANDWHERE VARCHAR(1000)='',--where語句 不用加where
@ORDERFEILD VARCHAR(100) --排序的欄位
as
DECLARE @EXECSQL VARCHAR(2000)
DECLARE @ORDERSTR VARCHAR(100)
DECLARE @ORDERBY VARCHAR(100)
BEGIN
set NOCOUNT on
IF @ORDERTYPE = 1
BEGIN
SET @ORDERSTR = ' > ( SELECT MAX(['+@ORDERFEILD+'])'
SET @ORDERBY = 'ORDER BY '+@ORDERFEILD+' ASC'
END
ELSE
BEGIN
SET @ORDERSTR = ' < ( SELECT MIN(['+@ORDERFEILD+'])'
SET @ORDERBY = 'ORDER BY '+@ORDERFEILD+' DESC'
END
IF @PAGE_INDEX = 1 --當頁碼是第一頁時直接運行,提高速度
BEGIN
IF @ANDWHERE=''
SET @EXECSQL = 'SELECT TOP '+STR(@PAGE_SIZE)+' '+@FEILDS+' FROM [books] '+@ORDERBY
ELSE
SET @EXECSQL = 'SELECT TOP '+STR(@PAGE_SIZE)+' '+@FEILDS+' FROM [books] WHERE '+@ANDWHERE+' '+ @ORDERBY
END
ELSE
BEGIN
IF @ANDWHERE=''
BEGIN --以子查詢結果當做新表時 要給表名別名才能用
SET @EXECSQL = 'SELECT TOP'+STR(@PAGE_SIZE)+' '+@FEILDS+' FROM [books] WHERE '+@ORDERFEILD+
@ORDERSTR+' FROM (SELECT TOP '+STR(@PAGE_SIZE*(@PAGE_INDEX-1))+' '+@ORDERFEILD+
' FROM [books] '+@ORDERBY+') AS TEMP) '+ @ORDERBY
END
ELSE
BEGIN
SET @EXECSQL = 'SELECT TOP'+STR(@PAGE_SIZE)+' '+@FEILDS+' FROM [books] WHERE '+@ORDERFEILD+
@ORDERSTR+' FROM (SELECT TOP '+ STR(@PAGE_SIZE*(@PAGE_INDEX-1))+' '+@ORDERFEILD+
' FROM [books] WHERE '+@ANDWHERE+' '+@ORDERBY+') AS TEMP) AND '+@ANDWHERE+' '+ @ORDERBY
END
END
EXEC (@EXECSQL)--這裡要加括弧
END
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.