1、AJAX简介
(1、没有AJAX会怎么样?普通的ASP.Net每次执行服务端方法的时候都要刷新当前页面,比如实现显示服务器的时间。每次都要刷新页面的坏处:页面刷新打断用户操作、速度慢、增加服务器的流量压力。如果没有AJAX,在youku看视频的过程中如果点击了“顶、踩”、评论、评论翻页,页面就会刷新,视频就会被打断。试想一个效果:在YOUKU网看视频,然后看到一个顶踩的功能,看没有ajax会打断视频,然后将按钮用UpdatePanel包起来就不会打断视频了。用HttpWatch看没有AJAX的时候服务器返回的是整个页面,有了AJAX服务器只返回几个按钮的内容。
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>AJAX01</title> 5 <script type="text/javascript"> 6 function btnClick() { 7 //alert(1); 8 // 1 创建XMLHTTP对象,相当于WebClient 9 var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 10 11 if (!xmlhttp) { 12 alert("创建xmlhttp对象异常"); 13 return; 14 } 15 16 // 2 “准备”01AJAX.ashx发出Post请求。这里还没有发出请求 17 //XMLHTTP默认(也推荐)不是同步请求的,也就是open方法并不像WebClient的DownloadString 18 //那样把服务器返回的数据拿到才返回, 19 //是异步的,因此需要监听onreadystatechange事件 20 21 22 xmlhttp.open("POST", "01AJAX.ashx?id=" + encodeURI('AJAX服务器') + "&ts=" + new Date(), false); 23 24 xmlhttp.onreadystatechange = function () { 25 if (xmlhttp.readyState == 4) {//readyState == 4 表示服务器返回数据了 26 if (xmlhttp.status == 200) {//如果状态码为200则是成功 27 //接收服务器的返回数据,没有用send的返回值,而是在onreadystatechange事件里来接收 28 document.getElementById("txtTime").value = xmlhttp.responseText; //responseText属性为服务器返回的文本 29 } 30 else { 31 alert("AJAX服务器返回错误!"); 32 } 33 } 34 } 35 //不要以为if(xmlhttp.readyState == 4) 在send之前执行!!!! 36 //if (xmlhttp.readyState == 4)只有在服务器返回值以后才会执行,而!!send之后过一会儿服务器才会返回数据 37 xmlhttp.send(); //这时才开始发送请求 38 } 39 </script> 40 </head> 41 <body> 42 <input type="text" id="txtTime" /> 43 <input type="button" id="btn" value="button" onclick="btnClick()" /> 44 </body> 45 </html>
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 6 namespace AJAX 7 { 8 /// <summary> 9 /// _01AJAx 的摘要说明 10 /// </summary> 11 public class _01AJAx : IHttpHandler 12 { 13 14 public void ProcessRequest(HttpContext context) 15 { 16 context.Response.ContentType = "text/plain"; 17 string id = context.Request["id"]; 18 context.Response.Write(DateTime.Now.ToString()+"---"+id); 19 } 20 21 public bool IsReusable 22 { 23 get 24 { 25 return false; 26 } 27 } 28 } 29 }
xmlhttp.open("POST","GetDate1.ashx?id=1&name="+"encodeURL('中国')", false),如果传递给服务器的请求里有中文,则需要使用Javascript函数encodeURI来进行URL编码。
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>02 huilv question</title> 5 <script src="js/jquery-1.4.2.js" type="text/javascript"></script> 6 <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script> 7 <script type="text/javascript"> 8 function btnOnclick() { 9 var moneyType = $("#selectedID").val(); 10 var account = $("#myaccount").val(); 11 //alert(account); 12 //alert(moneyType); 13 var xmlhttp =new ActiveXObject("Microsoft.XMLHTTP"); 14 if (!xmlhttp) { 15 alert("error from create xmlhttp!"); 16 return; 17 } 18 xmlhttp.open("POST", "02" + encodeURI('汇率问题') + ".ashx?moneyType=" + moneyType + "&account=" + account + "&ts=" + new Date(), false); 19 xmlhttp.onreadystatechange = function () { 20 if (xmlhttp.readyState == 4) { 21 alert(xmlhttp.responseText); 22 if (xmlhttp.status == 200) { 23 alert(xmlhttp.responseText); 24 //$("#result").text = xmlhttp.responseText; 25 $("#result").val(xmlhttp.responseText); 26 } 27 } 28 } 29 xmlhttp.send(); 30 } 31 32 </script> 33 </head> 34 <body> 35 <input id="myaccount" type="text" name="name" value="" /> 36 <select id="selectedID"> 37 <option value="1" selected="selected">dollar</option> 38 <option value="2">Japan</option> 39 <option value="3">Hongkong</option> 40 </select> 41 <input type="button" name="name" value="check" onclick="btnOnclick()" /> 42 <input type="text" name="name" value=" " id="result"/> 43 </body> 44 </html>
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 6 namespace AJAX 7 { 8 /// <summary> 9 /// _02汇率问题 的摘要说明 10 /// </summary> 11 public class _02汇率问题 : IHttpHandler 12 { 13 14 public void ProcessRequest(HttpContext context) 15 { 16 context.Response.ContentType = "text/plain"; 17 //context.Response.Write("Hello World"); 18 //get two accounts from html 19 string moneyType = context.Request["moneyType"]; 20 int account = Convert.ToInt32(context.Request["account"]); 21 22 if (moneyType == "1")//dollar 23 { 24 context.Response.Write(account/7); 25 } 26 else if(moneyType=="2")//Japan 27 { 28 context.Response.Write(account*10); 29 } 30 else//Hongkong 31 { 32 context.Response.Write(account*10/9); 33 } 34 } 35 36 public bool IsReusable 37 { 38 get 39 { 40 return false; 41 } 42 } 43 } 44 }
!!!遇到问题总结:
☆xmlhttp.open("POST", "02" + encodeURI('汇率问题') + ".ashx?moneyType=" + moneyType + "&account=" + account + "&ts=" + new Date(), false);这句代码中,用到中文字符都要用encodeURl来转化字符类型,不仅仅是参数,页面名称亦如是。
☆$("#result").val(xmlhttp.responseText);将xmlhttp获取得到的文本数据传给val()。
3、JQuery AJAX
1 function CreateXmlHttp() 2 3 { 4 5 varxmlhttp; 6 7 //非IE浏览器创建XmlHttpRequest对象 8 9 if (window.XmlHttpRequest) 10 11 { 12 13 xmlhttp =new XmlHttpRequest(); 14 15 } 16 17 //IE浏览器创建XmlHttpRequest对象 18 19 if (window.ActiveXObject) 20 21 { 22 23 try 24 25 { 26 27 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 28 29 } 30 31 catch (e) 32 33 { 34 35 try 36 37 { 38 39 xmlhttp = new ActiveXObject("msxml2.XMLHTTP"); 40 41 } 42 43 catch (ex) {alert("AJAX创建失败!");} 44 45 } 46 47 } 48 49 return xmlhttp; 50 51 }
(2、采用JQueryAJAX方式可以高效化解浏览器问题:JQuery中提供了简化ajax使用的方法。$.ajax()函数是JQuery中提供的ajax访问函数,
$.post()是对$.ajax()的post方式提交ajax查询的封装,$.get()是对$.ajax()的get方式提交ajax查询的封装。推荐用post方式,因为post方式没有缓存的问题。
案例1:对前面的汇率问题进行修改简化
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>02 huilv question</title> 5 <script src="js/jquery-1.4.2.js" type="text/javascript"></script> 6 <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script> 7 <script type="text/javascript"> 8 function btnOnclick_01() {//just test ,nothing 9 $.post("01AJAX.ashx", function (data, textSize) { 10 if (textSize == "success") { 11 alert(data); 12 } else { 13 alert("AJAX create a error!!!"); 14 } 15 }); 16 17 } 18 function btnOnclick_02() {// huilv question 19 var account = $("#myaccount").val(); 20 var moneyType = $("#selectedID").val(); 21 $.post("03JQuery" + encodeURI('汇率问题') + ".ashx", { "account": account, "moneyType": moneyType }, function (data, textSize) { 22 if (textSize == "success") { 23 alert(data); 24 } else { 25 alert("AJAX create a error!!!"); 26 } 27 }); 28 29 } 30 </script> 31 </head> 32 <body> 33 <input id="myaccount" type="text" name="name" value="" /> 34 <select id="selectedID"> 35 <option value="1" selected="selected">dollar</option> 36 <option value="2">Japan</option> 37 <option value="3">Hongkong</option> 38 </select> 39 <input type="button" name="name" value="Just_test" onclick="btnOnclick_01()" /> 40 <input type="button" name="name" value="check" onclick="btnOnclick_02()" /> 41 <input type="text" name="name" value=" " id="result"/> 42 </body> 43 </html>
4、练习
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>search the price problem</title> 5 <script src="js/jquery-1.4.2.js" type="text/javascript"></script> 6 <script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script> 7 <script type="text/javascript"> 8 $(function () { 9 $("#myinput").blur(function () { 10 var name = $("#myinput").val(); 11 $.post("GetPrice.ashx", { "name": name }, function (data, istatus) { 12 if (istatus == "success") { 13 var myArray = data.split("|"); 14 if (myArray[0] == "ok") { 15 $("#result").val(myArray[1]); 16 } 17 else if (myArray[0] == "none") { 18 alert("No Sale!"); 19 } else { 20 alert("error data!"); 21 } 22 } else { 23 alert("AJAX error!s"); 24 } 25 }); 26 }); 27 }); 28 </script> 29 </head> 30 <body> 31 <input id="myinput" type="text" name="name" value="" /> 32 <input type="text" name="name" value=" " id="result"/> 33 </body> 34 </html>
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using AJAX.DAL.DataSet1TableAdapters; 6 7 namespace AJAX 8 { 9 /// <summary> 10 /// _02汇率问题 的摘要说明 11 /// </summary> 12 public class GetPrice : IHttpHandler 13 { 14 15 public void ProcessRequest(HttpContext context) 16 { 17 context.Response.ContentType = "text/plain"; 18 //context.Response.Write("Hello World"); 19 string name = context.Request["name"]; 20 var data = new buyTableAdapter().GetDataByName(name); 21 if(data.Count<=0) 22 { 23 context.Response.Write("none|0"); 24 } 25 else 26 { 27 context.Response.Write("ok|"+data.Single().Price); 28 } 29 //context.Response.Write("happy"); 30 } 31 32 public bool IsReusable 33 { 34 get 35 { 36 return false; 37 } 38 } 39 } 40 }
!!!遇到问题总结:
☆发现错误,调试了半天,但是根本无法进入到应该处理的代码段进行调试。后来经过一番查找,得出原因!!!
我是直接从之前的其他页面拷贝整个ashx 文件然后修改成到现在的文件,VS2010 没有自动帮我修改ashx文件所指向的类,必须手工进行修改。
解决方法:右键点击该 ashx 文件,选择“查看标记”,在打开的编辑界面中,修改 Class 项,改为新项目所指向命名空间下的类名。
<%@ 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 }, function (data, 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>
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,完全静态操作
<!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", function (data, 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>
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;}
(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对像。
<!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", function (data, 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>
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实现无刷新评论列表分页
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; } } }
<!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" }, function (data, 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" }, function (data, 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", { "action": "getpagedata", "pagenum": $(this).text() }, function (data, 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实现无刷新删除评论
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; } } } }
<%@ 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 }, function (data, 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-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-1px;font-family: Verdana, Arial, Helvetica, 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, Arial, Helvetica, 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 中即可;
1.开发步骤:
①添加一个Web项目 在Web项目中新建”新建项”→”Web”→”启用了AJAX的WCF服务”
②页面上拖放ScriptManager控件 Services属性中新增一项 Path属性设置为服务路径
③调用服务端方法时
Service1.DoWork(OnDoWorkSuccess, OnDoWorkFailed);Service1为服务类名 DoWork为方法名 OnDoWorkSuccess为成功时回调函数 OnDoWorkFailed为失败时回调函数 两个函数都有一个参数result 成功时参数作为返回值 失败时参数作为错误消息。服务器端还可以返回复杂对象 浏览器端可以直接从result读取复杂对象的字段值
(1、"web" 全局应用程序类(注意文件名不要改)
①全局文件是对Web应用生命周期的一个事件响应的地方
②将Web应用启动时初始化的一些代码写到Application_Start中(如Log4Net等)
③Web应用关闭时Application_End调用
④Session启动时Session_Start调用
⑤Session结束(用户主动退出或者超时结束)时Session_End调用
⑥当一个用户请求来的时候Application_BeginRequest调用
⑦当应用程序中出现未捕获异常时Application_Error调用(通过HttpContext.Current.Server.GetLastError()获得异常信息 然后用Log4Net记录到日志中)
练习:禁止盗链和IP地址禁止
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重写
- SEO(Search Engine Optimization): 搜索引擎优化
- URL重写(URLRewrite 伪静态):搜索引擎优化也方便用户看
- Site:cnblogs.com 能看百度收录了多少网页
!!!实现:当打开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);
}