淺談Ajax在ASP.Net中的使用
Ajax在應用中使用有3個部分(個人觀點):
1.數(shù)據(jù)(一般通過IE內置組件Microsoft.XMLHTTP來取得或者發(fā)送數(shù)據(jù));
2.事件(事件指的是客戶端事件,如果是服務端事件,那么AJAX也就沒什么意義了);
3.綁定(暫且就叫綁定吧,也可以說是顯示,一般通過DHTML來完成)。
從上面看,Ajax就使用了Microsoft.XMLHTTP組件和DHTL。其實還有另外一部分,就是服務器端的處理。
一、簡單示例
就最簡單的原型來說,就是取得數(shù)據(jù):
a.aspx的內容如下:
< div id="MyShow"/>
< script language="JavaScript">
var xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
//數(shù)據(jù)傳輸,flase為非異步方式
xmlhttp.open("GET","a.aspx",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
MyShow.InnerText = xmlhttp.responseText;
}
if (xmlhttp.readyState==3) {
MyShow.InnerText = ('正在提交數(shù)據(jù)');
}
}
xmlhttp.send(null);
}
< /script>
a.aspx提供數(shù)據(jù)xmlhttp.open("GET","a.aspx",true);就是請求a.aspx
if (xmlhttp.readyState==4) {
MyShow.InnerText = xmlhttp.responseText;
}
|
當異步請求完成時,用DHML改變MyShow的內容。
二、GET方法
更改a.aspx如下:
< script runat="Server" language="C#">
string flag = Request["flag"] == null ? "" : Request["flag"];
switch(flag)
{
case "1":
Response.Write("11111111111111");
break;
case "2" :
Response.Write("22222222222222");
break;
}
< /script> |
把b.aspx中xmlhttp.open("GET","a.aspx",true);改成xmlhttp.open("GET","a.aspx?flag=1",true);
則得到數(shù)據(jù)11111111111111
xmlhttp.open("GET","a.aspx",true);改成xmlhttp.open("GET","a.aspx?flag=2",true);
則得到數(shù)據(jù)22222222222222
三、POST方法
如果有這樣一個表單
< form method=post> < input name="p1" type=text /> < input name="p2" type=submit/> < /form> |
用AJAX就是
< div id="MyShow"/>
< script language="JavaScript">
var xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
//數(shù)據(jù)傳輸,flase為非異步方式
xmlhttp.open("Post","a.aspx",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
MyShow.InnerText = xmlhttp.responseText;
}
if (xmlhttp.readyState==3) {
MyShow.InnerText = ('正在提交數(shù)據(jù)');
}
}
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send("p1=qwdqwdqwdqwd"); //這里是POST要提交的數(shù)據(jù)。
}
< /script>
而一般模擬請求都是POST和Get同時存在的。只要把xmlhttp.open("Post","a.aspx",true);里a.aspx加上get請求部分就可以了。
而在.Net中特別得,可以把Ajax寫成服務器組件來使用。現(xiàn)在在實際項目中如果使用Ajax很多的情況,就有個專門的組件來使用了。還有就是要注意,在很多時候Ajax的時候要設置頁面不緩存。而如果要兼容非IE內核瀏覽器,那么就要注意各種內核瀏覽器的JS是否兼容了。
【編輯推薦】

















