溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

asp.net中如何利用Jquery+Ajax+Json實現(xiàn)無刷新分頁

發(fā)布時間:2021-07-26 11:57:11 來源:億速云 閱讀:184 作者:chen 欄目:開發(fā)技術

本篇內容主要講解“asp.net中如何利用Jquery+Ajax+Json實現(xiàn)無刷新分頁”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“asp.net中如何利用Jquery+Ajax+Json實現(xiàn)無刷新分頁”吧!

復制代碼 代碼如下:


<%@ 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;     //每頁顯示條數(shù)初始化,修改顯示條數(shù),修改這里即可
    $(function () {
        InitTable(0);    //Load事件,初始化表格數(shù)據(jù),頁面索引為0(第一頁)  
        //分頁,PageCount是總條目數(shù),這是必選參數(shù),其它參數(shù)都是可選
        $("#Pagination").pagination(<%=pageCount %>, {
            callback: PageCallback,
            prev_text: '上一頁',       //上一頁按鈕里text
            next_text: '下一頁',       //下一頁按鈕里text
            items_per_page: pageSize,  //顯示條數(shù)
            num_display_entries: 6,    //連續(xù)分頁主體部分分頁條目數(shù)
            current_page: pageIndex,   //當前頁索引
            num_edge_entries: 2        //兩側首尾分頁條目數(shù)
        });

        //翻頁調用
        function PageCallback(index, jq) {
            InitTable(index);
        }

        //請求數(shù)據(jù)
        function InitTable(pageIndex) {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: 'SupplyAJAX.aspx',      //提交到一般處理程序請求數(shù)據(jù)
                data: "type=show&random=" + Math.random() + "&pageIndex=" + (pageIndex + 1) + "&pageSize=" + pageSize, //提交兩個參數(shù):pageIndex(頁面索引),pageSize(顯示條數(shù))   
                error: function () { alert('error data'); },  //錯誤執(zhí)行方法 
                success: function (data) {
                    $("#Result tr:gt(0)").remove();        //移除Id為Result的表格里的行,從第二行開始(這里根據(jù)頁面布局不同頁變)
                    var json = data; //數(shù)組
                    var html = "";
                    $.each(json.data, function (index, item) {
                        //循環(huán)獲取數(shù)據(jù) 
                        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);             //將返回的數(shù)據(jù)追加到表格
                }
            });
        }
    });
    </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; //總條目數(shù)

    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返回的數(shù)據(jù)
    /// <summary>
    /// 后臺獲取ashx返回的數(shù)據(jù)
    /// </summary>
    /// <param name="relativePath">地址</param>
    /// <param name="data">參數(shù)</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 分頁配置
                //具體的頁面數(shù)
                int pageIndex;
                int.TryParse(Request["pageIndex"], out pageIndex);
                //頁面顯示條數(shù)
                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 模擬數(shù)據(jù)
    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> 
    /// 獲取總頁數(shù) 
    /// </summary> 
    /// <param name="sumCount">結果集數(shù)量</param> 
    /// <param name="pageSize">頁面數(shù)量</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;
    } 
}

到此,相信大家對“asp.net中如何利用Jquery+Ajax+Json實現(xiàn)無刷新分頁”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI