本文实例讲述了C#使用WebService结合jQuery实现无刷新翻页的方法。分享给大家供大家参考。具体如下:
1. 首先创建数据库、表Article,字段ArticleId,Title
前台代码
<%@ Page Language="C#" AutoEventWireup="true" %><!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 id="Head1" runat="server"><title></title><script src="jquery-1.6.4.min.js" type="text/javascript"></script></head><body> <form id="form1" runat="server"> <div id="result"> </div> </form> <script type="text/javascript"> var pageNo = 1; //当前页号 var pageItems = 10; //每页显示的行数,这个数字与da.Fill(ds,pageNo,3,"gbook");里面的3保持一致 var MaxPage = pageItems; function showPage(m) { if (m == -1) { if (pageNo < 2) { alert("已经到了首页"); return; }; MaxPage = pageItems; } else { if (MaxPage < pageItems) { alert("已经到了末页"); return; }; } pageNo += m; getData(); } $(document).ready(function () { getData(); }); function getData() { $.ajax({ type: "POST", cache: false, url: "WebService3.asmx/Select", /* 注意后面的名字对应CS的方法名称 */ data: { "pageNo": (pageNo - 1) * pageItems }, /* 注意参数的格式和名称 */ contentType: "application/x-www-form-urlencoded", dataType: "xml", error: function (result) { alert(result.responseText); }, success: function (data) { MaxPage = $(data).find('Article').size(); /* Article是后台输出的表名称,要与后台对应 */ if (MaxPage == 0) { $("#result").html("没有记录"); return; } t = "<table border='1'>"; $(data).find('Article').each(function (index, ele) { /* Article是后台输出的表名称,要与后台对应 */ var ArticleId = $(ele).find('ArticleId').text(); var Title = $(ele).find('Title').text(); t += "<tr>"; t += "<td>" + ArticleId + "</td>"; t += "<td>" + Title + "</td>"; t += "</tr>"; }) t += "</table>"; t += "<div><a href='' onclick='showPage(-1);return false;'>上一页</a> <a href='' onclick='showPage(1);return false;'>下一页</a></div>" $("#result").html(t); } }); } </script></body></html>
2. 后台代码
using System.Data;using System.Data.SqlClient;using System;using System.Web;using System.Web.Services;using System.Web.Services.Protocols;[WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释[System.Web.Script.Services.ScriptService]public class WebService3 : System.Web.Services.WebService{ [WebMethod] public System.Data.DataSet Select(int pageNo) { System.Data.SqlClient.SqlConnection sqlCon = new SqlConnection(); sqlCon.ConnectionString = "server=.;uid=sa;pwd=sa;database=guestbook"; //定义SQL语句 string SqlStr = "SELECT ArticleId,Title FROM Article ORDER BY ArticleId DESC"; //实例化SqlDataAdapter对象 SqlDataAdapter da = new SqlDataAdapter(SqlStr, sqlCon); DataSet ds = new DataSet(); da.Fill(ds, pageNo, 10, "Article"); return ds; }}
希望本文所述对大家的C#程序设计有所帮助。
新闻热点
疑难解答