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 项,改为新项目所指向命名空间下的类名。
方法2:评论和列表均采用AJAX,完全静态操作
总结:如果想要控制用户的评论,例如禁止用户输入粗话等不文明用语,可以在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对像。
总结:JavaScriptSerializer要引用using System.Web.Script.Serialization;但是using System.Web.Script.Serialization;引用的前提是引用System.web.extensions.dll
练习2:用Json实现无刷新评论列表分页
练习3:用Json实现无刷新删除评论
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);
}
来源:http://www.cnblogs.com/daomul/archive/2013/04/29/3046449.html