.NET运用AJAX 总结及其实例
1、AJAX简介 (1、没有AJAX会怎么样?普通的ASP.Net每次执行服务端方法的时候都要刷新当前页面,比如实现显示服务器的时间。每次都要刷新页面的坏处:页面刷新打断用户操作、速度慢、增加服务器的流量压力。如果没有AJAX,在youku看视频的过程中如果点击了“顶、踩”、评论、评论翻页,页面就会刷新,视频就会被打断。试想一个效果:在YOUKU网看视频,然后看到一个顶踩的功能,看没有ajax会打断视频,然后将按钮用UpdatePanel包起来就不会打断视频了。用HttpWatch看没有AJAX的时候服务器返回的是整个页面,有了AJAX服务器只返回几个按钮的内容。
(2、AJAX(AsynchronousJavaScript and XML,异步JavaScript和XML)是一种进行页面局部异步刷新的技术。用AJAX向服务器发送请求和获得服务器返回的数据并且更新到界面中,不是整个页面刷新,而是在HTML页面中使用JavaScript创建XMLHTTPRequest对象来向服务器发出请求以及获得返回的数据,就像JavaScript版的WebClient一样,在页面中由XMLHTTPRequest来发出Http请求和获得服务器的返回数据,这样页面就不会刷新了。XMLHTTPRequest是AJAX的核心对象。 2、XMLHTTPRequest
(1、开发一个AJAX功能需要开发服务端和客户端两块程序。以一个显示服务端时间为例。首先开发一个GetDate1.ashx,输出当前时间。在HTML页面中放一个按 钮,在按钮的onclick中创建XMLHTTP向GetDate1.ashx发送请求,获得返回的数据并且显示到界面上。下面的代码非常重要,是精华来着,必背:
javascript代码 <!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>AJAX01</title> <script type="text/javascript"> function btnClick() { //alert(1); // 1 创建XMLHTTP对象,相当于WebClient var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); if (!xmlhttp) { alert("创建xmlhttp对象异常"); return; } // 2 “准备”01AJAX.ashx发出Post请求。这里还没有发出请求 //XMLHTTP默认(也推荐)不是同步请求的,也就是open方法并不像WebClient的DownloadString //那样把服务器返回的数据拿到才返回, //是异步的,因此需要监听onreadystatechange事件 xmlhttp.open("POST","01AJAX.ashx?id=" + encodeURI('AJAX服务器') + "&ts=" + new Date(),false); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) {//readyState == 4 表示服务器返回数据了 if (xmlhttp.status == 200) {//如果状态码为200则是成功 //接收服务器的返回数据,没有用send的返回值,而是在onreadystatechange事件里来接收 document.getElementById("txtTime").value = xmlhttp.responseText; //responseText属性为服务器返回的文本 } else { alert("AJAX服务器返回错误!"); } } } //不要以为if(xmlhttp.readyState == 4) 在send之前执行!!!! //if (xmlhttp.readyState == 4)只有在服务器返回值以后才会执行,而!!send之后过一会儿服务器才会返回数据 xmlhttp.send(); //这时才开始发送请求 } </script> </head> <body> <input type="text" id="txtTime" /> <input type="button" id="btn" value="button" onclick="btnClick()" /> </body> </html> ashx代码 using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AJAX { /// <summary> /// _01AJAx 的摘要说明 /// </summary> public class _01AJAx : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string id = context.Request["id"]; context.Response.Write(DateTime.Now.ToString()+"---"+id); } public bool IsReusable { get { return false; } } } }
(2、不使用UpdatePanel、JQuery等AJAX库编写一个AJAX程序。 也可以在xmlhttp.open中向服务器传递参数:
xmlhttp.open("POST","GetDate1.ashx?id=1&name="+"encodeURL('中国')",false),如果传递给服务器的请求里有中文,则需要使用Javascript函数encodeURI来进行URL编码。 (3、发出请求后不等服务器返回数据,就继续向下执行,所以不会阻塞,界面就不卡了,这就是AJAX中“A”的含义“异步”。只有在服务器返回值以后才会执
行,而!!send之后过一会儿服务器才会返回数据。
(4、 xmlhttp.open("GET",false),如果这样单纯滴传两个静态参数的话,浏览器可能会保持一
种提取缓存的状态,所以最好传一个动态参数,随意一个参数。这是一个AJAX缓冲存在的问题。如果用POST的方式,就不会发生缓冲的问题。
案例1:无刷新异步操作-->汇率转换
html代码 <!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>02 huilv question</title> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script> <script type="text/javascript"> function btnOnclick() { var moneyType = $("#selectedID").val(); var account = $("#myaccount").val(); //alert(account); //alert(moneyType); var xmlhttp =new ActiveXObject("Microsoft.XMLHTTP"); if (!xmlhttp) { alert("error from create xmlhttp!"); return; } xmlhttp.open("POST","02" + encodeURI('汇率问题') + ".ashx?moneyType=" + moneyType + "&account=" + account + "&ts=" + new Date(),false); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) { alert(xmlhttp.responseText); if (xmlhttp.status == 200) { alert(xmlhttp.responseText); //$("#result").text = xmlhttp.responseText; $("#result").val(xmlhttp.responseText); } } } xmlhttp.send(); } </script> </head> <body> <input id="myaccount" type="text" name="name" value="" /> <select id="selectedID"> <option value="1" selected="selected">dollar</option> <option value="2">Japan</option> <option value="3">Hongkong</option> </select> <input type="button" name="name" value="check" onclick="btnOnclick()" /> <input type="text" name="name" value=" " id="result"/> </body> </html> ashx代码 using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AJAX { /// <summary> /// _02汇率问题 的摘要说明 /// </summary> public class _02汇率问题 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); //get two accounts from html string moneyType = context.Request["moneyType"]; int account = Convert.ToInt32(context.Request["account"]); if (moneyType == "1")//dollar { context.Response.Write(account/7); } else if(moneyType=="2")//Japan { context.Response.Write(account*10); } else//Hongkong { context.Response.Write(account*10/9); } } public bool IsReusable { get { return false; } } } }!!!遇到问题总结: ☆xmlhttp.open("POST",false);这句代码中,用到中文字符都要用encodeURl来转化字符类型,不仅仅是参数,页面名称亦如是。 ☆$("#result").val(xmlhttp.responseText);将xmlhttp获取得到的文本数据传给val()。 3、JQuery AJAX
(1、newActiveXObject("Microsoft.XMLHTTP")是IE中创建XMLHttpRequest对象的方法。非IE浏览器中创建方法是newXmlHttpRequest()。为了兼容不同的浏览 器需要编写很多代码,下面的兼容浏览器也不是很完整的:
兼容不同浏览器的XMLhttpresquest对象 function CreateXmlHttp() { varxmlhttp; //非IE浏览器创建XmlHttpRequest对象 if (window.XmlHttpRequest) { xmlhttp =new XmlHttpRequest(); } //IE浏览器创建XmlHttpRequest对象 if (window.ActiveXObject) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("msxml2.XMLHTTP"); } catch (ex) {alert("AJAX创建失败!");} } } return xmlhttp; } (2、采用JQueryAJAX方式可以高效化解浏览器问题:JQuery中提供了简化ajax使用的方法。$.ajax()函数是JQuery中提供的ajax访问函数, $.post()是对$.ajax()的post方式提交ajax查询的封装,$.get()是对$.ajax()的get方式提交ajax查询的封装。推荐用post方式,因为post方式没有缓存的问题。 JQuery改进汇率兑换问题 <!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>02 huilv question</title> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script> <script type="text/javascript"> function btnOnclick_01() {//just test,nothing $.post("01AJAX.ashx",function (data,textSize) { if (textSize == "success") { alert(data); } else { alert("AJAX create a error!!!"); } }); } function btnOnclick_02() {// huilv question var account = $("#myaccount").val(); var moneyType = $("#selectedID").val(); $.post("03JQuery" + encodeURI('汇率问题') + ".ashx",{ "account": account,"moneyType": moneyType },textSize) { if (textSize == "success") { alert(data); } else { alert("AJAX create a error!!!"); } }); } </script> </head> <body> <input id="myaccount" type="text" name="name" value="" /> <select id="selectedID"> <option value="1" selected="selected">dollar</option> <option value="2">Japan</option> <option value="3">Hongkong</option> </select> <input type="button" name="name" value="Just_test" onclick="btnOnclick_01()" /> <input type="button" name="name" value="check" onclick="btnOnclick_02()" /> <input type="text" name="name" value=" " id="result"/> </body> </html> 4、练习 练习1:JQuery实现Ajax 根据商品名称自动显示价格
html代码 <!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>search the price problem</title> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#myinput").blur(function () { var name = $("#myinput").val(); $.post("GetPrice.ashx",{ "name": name },istatus) { if (istatus == "success") { var myArray = data.split("|"); if (myArray[0] == "ok") { $("#result").val(myArray[1]); } else if (myArray[0] == "none") { alert("No Sale!"); } else { alert("error data!"); } } else { alert("AJAX error!s"); } }); }); }); </script> </head> <body> <input id="myinput" type="text" name="name" value="" /> <input type="text" name="name" value=" " id="result"/> </body> </html> ashx代码 using System; using System.Collections.Generic; using System.Linq; using System.Web; using AJAX.DAL.DataSet1TableAdapters; namespace AJAX { /// <summary> /// _02汇率问题 的摘要说明 /// </summary> public class GetPrice : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); string name = context.Request["name"]; var data = new buyTableAdapter().GetDataByName(name); if(data.Count<=0) { context.Response.Write("none|0"); } else { context.Response.Write("ok|"+data.Single().Price); } //context.Response.Write("happy"); } public bool IsReusable { get { return false; } } } } !!!遇到问题总结: ☆发现错误,调试了半天,但是根本无法进入到应该处理的代码段进行调试。后来经过一番查找,得出原因!!! 我是直接从之前的其他页面拷贝整个ashx 文件然后修改成到现在的文件,VS2010 没有自动帮我修改ashx文件所指向的类,必须手工进行修改。 解决方法:右键点击该 ashx 文件,选择“查看标记”,在打开的编辑界面中,修改 Class 项,改为新项目所指向命名空间下的类名。
练习2:无刷新评论帖子
方法1:评论采用AJAX,但采用Repeater动态显示列表
html代码 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ReviewByRepeater.aspx.cs" Inherits="AJAX.ReviewByRepeater1" %> <!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></title> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#Button1").click(function () { var msg = $("#TextArea1").val(); $.post("ReviewByRepeater.ashx",{ "msg": msg },istaus) { if (istaus != "success") { alert("failed!"); return; } if (data == "ok") { var newComment = $("<li>PostDate:" + new Date() + "IP:me,内容:" + msg + "</li>"); $("#ulCommentId").append(newComment); alert("success!"); } else { alert("error!"); } }); }); }); </script> </head> <body> <form id="form1" runat="server"> <div> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DeleteMethod="Delete" InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" SelectMethod="GetData" TypeName="AJAX.DAL.DataSet1TableAdapters.T_PostsTableAdapter" UpdateMethod="Update"> <DeleteParameters> <asp:Parameter Name="Original_ID" Type="Int64" /> </DeleteParameters> <InsertParameters> <asp:Parameter Name="IPAdrr" Type="String" /> <asp:Parameter Name="Msg" Type="String" /> <asp:Parameter Name="PostDate" Type="DateTime" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="IPAdrr" Type="String" /> <asp:Parameter Name="Msg" Type="String" /> <asp:Parameter Name="PostDate" Type="DateTime" /> <asp:Parameter Name="Original_ID" Type="Int64" /> </UpdateParameters> </asp:ObjectDataSource> <ul id="ulCommentId"> <asp:Repeater ID="Repeater1" runat="server" DataSourceID="ObjectDataSource1"> <ItemTemplate><li>Posdate:<%#Eval("PostDate") %>,IP:<%#Eval("IPAdrr") %>,内容:<%#Eval("Msg") %></li></ItemTemplate> </asp:Repeater> </ul> <br /> <textarea id="TextArea1" cols="20" rows="2"></textarea> <input id="Button1" type="button" value="button" /> </div> </form> </body> </html> ashx代码 using System; using System.Collections.Generic; using System.Linq; using System.Web; using AJAX.DAL.DataSet1TableAdapters; namespace AJAX { /// <summary> /// ReviewByRepeater 的摘要说明 /// </summary> public class ReviewByRepeater : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); string msg = context.Request["msg"]; new T_PostsTableAdapter().Insert(context.Request.UserHostAddress,msg,DateTime.Now); context.Response.Write("ok"); } public bool IsReusable { get { return false; } } } }方法2:评论和列表均采用AJAX,完全静态操作 html代码 <!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></title> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $.post("ReviewByAjax.ashx",istaus) { alert(data); //alert(istaus); if (istaus != "success") { $("#bodyComment").append($("<li>加载失败</li>")); } var mydata = data.split("$"); for (var i = 0; i < mydata.length; i++) { var rowdata = mydata[i].split("|"); var comment = $("<li> IP:" + rowdata[0] + ",PostDate:" + rowdata[1] + ",内容:" + rowdata[2]+"</li>"); $("#bodyComment").append(comment); } }); }); </script> </head> <body id="bodyComment"> </body> </html> ashx代码 using System; using System.Collections.Generic; using System.Linq; using System.Web; using AJAX.DAL.DataSet1TableAdapters; using System.Text; namespace AJAX { /// <summary> /// ReviewByAjax1 的摘要说明 /// </summary> public class ReviewByAjax : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); var comments = new T_PostsTableAdapter().GetData(); StringBuilder sb = new StringBuilder(); foreach (var comment in comments) { sb.Append(comment.IPAdrr).Append("|").Append(comment.PostDate) .Append("|").Append(comment.Msg).Append("$"); } context.Response.Write(sb.ToString().Trim('$')); } public bool IsReusable { get { return false; } } } } 总结:如果想要控制用户的评论,例如禁止用户输入粗话等不文明用语,可以在ashx文件中添加 if(Msg.Contains("粗话")){return;}
5、Json
(1、ajax传递复杂数据如果自己进行格式定义的话会经历组装、解析的过程。因此ajax中有一个事实上的数据传输标准json,json将复杂对像序列化为一个字符串,在浏览端再将字符串反序列化为javascript可以读取的对像,看一下json的格式,json被几乎所有语言支持。
(2、c#中将.net对像序列化为json字符串的方法:javascriptserializer().serialize(p),javascriptSerializer在System.web.extensions.dll中,是net3.x中新增的类,如果在.net2.0则需要用第三方的组件。
(3、Jquery ajax得到的data是Json格式数据,用$.parseJSON(data)方法将json格式数据解析为javaScript对像。 练习1:用Json实现类中数据的传递
html代码 <!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></title> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $.post("JsonText01.ashx",istaus) { var post = $.parseJSON(data); /*例子测试 1 */ //alert(post.PostDate); /*例子测试 2 */ //alert(post[0]); /*例子测试 3 */ alert(post[1].PostDate); }); }); </script> </head> <body id="bodyComment"> </body> </html> ashx代码 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization; namespace AJAX { /// <summary> /// JsonText01 的摘要说明 /// </summary> public class JsonText01 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); JavaScriptSerializer jss=new JavaScriptSerializer(); /*测试用例1 string myJson = jss.Serialize(new Post() { PostDate = "2012-09-10",Msg="send new Mag!" }); context.Response.Write(myJson);*/ /*测试用例2 string myJson = jss.Serialize(new string[] {"2012-09-10","send new Mag!" }); context.Response.Write(myJson);*/ /*测试用例3*/ Post[] posts = new Post[] { new Post() {PostDate = "2012-09-10",Msg = "send old Mag!"},new Post() {PostDate = "2013-01-12",Msg = "send new Mag!"} }; string myJson = jss.Serialize(posts); context.Response.Write(myJson); } //q1: //JavaScriptSerializer要引用using System.Web.Script.Serialization; public bool IsReusable { get { return false; } } } public class Post { public string PostDate { set; get; } public string Msg { get; set; } } } 总结:JavaScriptSerializer要引用using System.Web.Script.Serialization;但是using System.Web.Script.Serialization;引用的前提是引用System.web.extensions.dll 练习2:用Json实现无刷新评论列表分页 ashx代码 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization; using AJAX.DAL.DataSet1TableAdapters; //高效分页 namespace AJAX { /// <summary> /// JsonText02 的摘要说明 /// </summary> public class JsonText02 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string action = context.Request["action"]; if (action == "getpagecount") //如果请求的参数是getpagecount(获取页数) { var adapter = new T_PostsTableAdapter(); int count = adapter.ScalarQuery().Value; //获取数据总条数 int pageCount = count / 10; //每页只显示10条 if (count % 10 != 0) //如果数据不够10条,则只显示第一页 { pageCount++; } context.Response.Write(pageCount); //返回页数 } else if (action == "getpagedata") //如果请求的的参数是getpagedata(获取评论内容) { string pagenum = context.Request["pagenum"]; //获取客户端点击的是哪一页 int iPageNum = Convert.ToInt32(pagenum); var adapter = new T_PostsTableAdapter(); // (iPageNum-1)*10+1 第一条数据,(iPageNum)*10 最后一条数据; var data = adapter.GetPageData((iPageNum - 1) * 10 + 1,(iPageNum) * 10); List<Comment> list = new List<Comment>(); //由于数据过于复杂所引发异常,定义一个Comment的类,内有postDate,comment两个属性; foreach (var row in data) //遍历data { list.Add(new Comment() { PostDate = row.PostDate.ToShortDateString(),Msg = row.Msg,IPAdrr = row.IPAdrr }); } JavaScriptSerializer jss = new JavaScriptSerializer(); context.Response.Write(jss.Serialize(list)); //返回序列化的数据; } } public bool IsReusable { get { return false; } } } public class Comment { public string PostDate { get; set; } public string Msg { get; set; } public string IPAdrr { get; set; } } } html代码 <!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></title> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script> <style type="text/css"> ul { list-style: none; margin: 0px; padding: 0px; } li { border-bottom: 1px dashed #000; padding: 5px; font-family: "微软雅黑"; font-size: 12px; } .column { width: 80%; margin: 100px auto; padding: 10px; border: 1px solid #000; } p { background: #CCC; padding: 10px; } .divstyle { min-height: 50px; padding: 10px; } .trPage { } </style> <script type="text/javascript" language="javascript"> $(function () { //请求默认显示第一页数据 $.post("JsonText02.ashx",{ "action": "getpagedata","pagenum": "1" },status) { alert(1); if (status == "success") { var comments = $.parseJSON(data); $("#ulComments li").remove(); //首先清空上一次的数据; for (var i = 0; i < comments.length; i++) { var comment = comments[i]; var li = $("<li><p>回复日期:" + comment.PostDate + "回复IP地址:" + comment.IPAdrr + "</p><div class='divstyle'>" + comment.Msg + "</div></li>"); $("#ulComments").append(li); } } }); $.post("JsonText02.ashx",{ "action": "getpagecount" },status) { for (var i = 1; i <= data; i++) { var td = $("<td><a href=''>" + i + "</a></td>"); $(".trPage").append(td); } //给链接添加click事件 $(".trPage td").click(function (e) { e.preventDefault(); $.post("JsonText02.ashx","pagenum": $(this).text() },status) { var comments = $.parseJSON(data); //使用JSON序列化数据; $("#ulComments li").remove(); //首先清空上一次的数据; for (var i = 0; i < comments.length; i++) { //遍历响应的数据data var comment = comments[i]; //取到每条评论 //最后向ul中加载li(数据的内容) var li = $("<li><p>回复日期:" + comment.PostDate + "回复IP地址:" + comment.IPAdrr + "</p><div class='divstyle'>" + comment.Msg + "</div></li>"); $("#ulComments").append(li); } }); }); }); }); </script> </head> <body> <div class="column"> <table> <tr class="trPage"> </tr> </table> <ul id="ulComments"> </ul> <table> <tr class="trPage"> </tr> </table> </div> </body> </html> select * from ( SELECT ID,PostDate,Msg,IPAdrr,Row_Number() over(order by PostDate desc) rownum FROM dbo.T_Posts )t where t.rownum>=@startRowIndex and t.rownum<=@endRowIndex练习3:用Json实现无刷新删除评论 ashx代码 using System; using System.Collections.Generic; using System.Linq; using System.Web; using AJAX.DAL.DataSet1TableAdapters; namespace AJAX { /// <summary> /// JsonDelete03 的摘要说明 /// </summary> public class JsonDelete03 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); string id = context.Request["ID"]; new T_PostsTableAdapter().DeleteById(Convert.ToInt32(id)); } public bool IsReusable { get { return false; } } } } aspx代码 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JsonDelete03.aspx.cs" Inherits="AJAX.JsonDelete031" %> <!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></title> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("input[isDelete=true]").click(function () { var myID = $(this).attr("id"); $.post("JsonDelete03.ashx",{ "ID": myID },istaus) { if (istaus == "success") { alert("删除成功!"); //在这里,$(this)指的不是控件本身而是这个位置 $("input[id=" + myID + "]").parent().parent().remove("tr"); } else { alert("删除失败,请联系管理员"); } }); }); }); </script> </head> <body> <form id="form1" runat="server"> <div> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DeleteMethod="Delete" InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" SelectMethod="GetData" TypeName="AJAX.DAL.DataSet1TableAdapters.T_PostsTableAdapter" UpdateMethod="Update"> <DeleteParameters> <asp:Parameter Name="Original_ID" Type="Int64" /> </DeleteParameters> <InsertParameters> <asp:Parameter Name="IPAdrr" Type="String" /> <asp:Parameter Name="Msg" Type="String" /> <asp:Parameter Name="PostDate" Type="DateTime" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="IPAdrr" Type="String" /> <asp:Parameter Name="Msg" Type="String" /> <asp:Parameter Name="PostDate" Type="DateTime" /> <asp:Parameter Name="Original_ID" Type="Int64" /> </UpdateParameters> </asp:ObjectDataSource> </div> <asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" DataSourceID="ObjectDataSource1" InsertItemPosition="LastItem"> <edititemtemplate> <tr style="background-color: #999999;"> <td> <asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="更新" /> <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="取消" /> </td> <td> <asp:Label ID="IDLabel1" runat="server" Text='<%# Eval("ID") %>' /> </td> <td> <asp:TextBox ID="IPAdrrTextBox" runat="server" Text='<%# Bind("IPAdrr") %>' /> </td> <td> <asp:TextBox ID="MsgTextBox" runat="server" Text='<%# Bind("Msg") %>' /> </td> <td> <asp:TextBox ID="PostDateTextBox" runat="server" Text='<%# Bind("PostDate") %>' /> </td> </tr> </edititemtemplate> <emptydatatemplate> <table runat="server" style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;"> <tr> <td> 未返回数据。</td> </tr> </table> </emptydatatemplate> <insertitemtemplate> <tr style=""> <td> <asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="插入" /> <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="清除" /> </td> <td> </td> <td> <asp:TextBox ID="IPAdrrTextBox" runat="server" Text='<%# Bind("IPAdrr") %>' /> </td> <td> <asp:TextBox ID="MsgTextBox" runat="server" Text='<%# Bind("Msg") %>' /> </td> <td> <asp:TextBox ID="PostDateTextBox" runat="server" Text='<%# Bind("PostDate") %>' /> </td> </tr> </insertitemtemplate> <itemtemplate> <tr style="background-color: #E0FFFF;color: #333333;"> <td> <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="删除" /> <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="编辑" /> <input type="button" isDelete="true" id='<%# Eval("ID") %>' value=" 无刷新删除" /> </td> <td> <asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' /> </td> <td> <asp:Label ID="IPAdrrLabel" runat="server" Text='<%# Eval("IPAdrr") %>' /> </td> <td> <asp:Label ID="MsgLabel" runat="server" Text='<%# Eval("Msg") %>' /> </td> <td> <asp:Label ID="PostDateLabel" runat="server" Text='<%# Eval("PostDate") %>' /> </td> </tr> </itemtemplate> <layouttemplate> <table runat="server"> <tr runat="server"> <td runat="server"> <table ID="itemPlaceholderContainer" runat="server" border="1" style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;font-family: Verdana,Arial,sans-serif;"> <tr runat="server" style="background-color: #E0FFFF;color: #333333;"> <th runat="server"> </th> <th runat="server"> ID</th> <th runat="server"> IPAdrr</th> <th runat="server"> Msg</th> <th runat="server"> PostDate</th> </tr> <tr ID="itemPlaceholder" runat="server"> </tr> </table> </td> </tr> <tr runat="server"> <td runat="server" style="text-align: center;background-color: #5D7B9D;font-family: Verdana,sans-serif;color: #FFFFFF"> <asp:DataPager ID="DataPager1" runat="server"> <Fields> <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowLastPageButton="True" /> </Fields> </asp:DataPager> </td> </tr> </table> </layouttemplate> <selecteditemtemplate> <tr style="background-color: #E2DED6;font-weight: bold;color: #333333;"> <td> <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="删除" /> <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="编辑" /> </td> <td> <asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' /> </td> <td> <asp:Label ID="IPAdrrLabel" runat="server" Text='<%# Eval("IPAdrr") %>' /> </td> <td> <asp:Label ID="MsgLabel" runat="server" Text='<%# Eval("Msg") %>' /> </td> <td> <asp:Label ID="PostDateLabel" runat="server" Text='<%# Eval("PostDate") %>' /> </td> </tr> </selecteditemtemplate> </asp:ListView> </form> </body> </html> 6、微软中的AJAX应用 (1、ASP.NET中内置的简化AJAX开发的控件UPdatePanel ☆放入ScriptManager,将要实现AJAX效果的控件放到UpdatePanel 中即可;
☆ UpdatePanel远离揭秘,用httpWatch看
原理:
缺点:通讯量傻瓜化过大,浪费流量,适合企业内部用。Timer就是实现定时AJAX效果,但是数据量也很大
☆只需要把无刷新更新的部分放到UPdatePanel中
(2、用WCF简化AJAX代码量,让javascript写C#代码
(3、UpdateProgress显示正在加载
7、WCF了解
1.开发步骤: 8、全局文件
(1、"web" 全局应用程序类(注意文件名不要改) ①全局文件是对Web应用生命周期的一个事件响应的地方 练习:禁止盗链和IP地址禁止 Global.asax using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; namespace AJAX { public class Global : System.Web.HttpApplication { //程序启动的时候执行的代码 protected void Application_Start(object sender,EventArgs e) { } //调用Session信息开始 protected void Session_Start(object sender,EventArgs e) { //HttpContext.Current.Session.Abandon();//结束Session } //每次请求都会触发 protected void Application_BeginRequest(object sender,EventArgs e) { //通过HttpContext.Current.Request.Url查看来源 //用途1:可以在这里屏蔽IP地址 if(HttpContext.Current.Request.UserHostAddress=="127.0.0.1") { HttpContext.Current.Response.Write("已屏蔽,请联系管理员"); HttpContext.Current.Response.End(); } //用途2:防盗链 if(HttpContext.Current.Request.Url.AbsolutePath.EndsWith("/JPG")&& HttpContext.Current.Request.UrlReferrer.Host!="localhost") { //localhost:如果是正式上线则是域名地址 HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("~/DSCF0802.JPG")); HttpContext.Current.Response.End(); } } protected void Application_AuthenticateRequest(object sender,EventArgs e) { } //程序发生异常的时候,就会被捕获,抛出异常(ASP.NET错误处理:错误页和Application_Error) protected void Application_Error(object sender,EventArgs e) { /*如果在aspx页面中 throw new exception("error"); HttpContext.Current.Server.GetLastError()获得异常信息, * 然后用log4Net记录到错误处理机制中 */ } //Session时间到后终止 protected void Session_End(object sender,EventArgs e) { } //程序结束的时候执行的代码(只执行一次) protected void Application_End(object sender,EventArgs e) { } } } 9、URL重写
!!!实现:当打开View-1.aspx、View-2.aspx重写,都是指向同一个页面 原理: 在Global.asax的Application_BeginRequest中读取请求的URL并使用HttpContext.Current.Rewrite()进行重写 Regex reg = new Regex(“.+View-(d+).aspx”); var m1 = reg.Match(HttpContext.Current.Request.Url.AbsolutePath); if(macth.Success) { string id = match.Groups[1].Value; HttpContext.Current.RewitePath(“View.aspx?id=” + id); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |