什么是ajax
AJAX:”Asynchronous JavaScript and XML”
中文意思:異步JavaScript和XML
指一種創建交互式網頁應用的網頁開發技術。
不是指一種單一的技術,而是有機地利用了一系列相關的技術:
簡單理解為:JavaScript + XMLHttpRequest + CSS +服務器端 的集合
普通的網頁請求回執過程(請求響應模式 同步模式)
ajax 網頁應用 異步請求回執過程:通過和普通模式相比,就感覺ajax方式,就好比專門請了一個人去做一一件事,互不影響。
AJAX優點
• Ajax在本質上是一個瀏覽器端的技術
• Ajax技術之主要目的在於局部交換客戶端及服務器間之數據
• 這個技術的主角XMLHttpRequest 的最主要特點,在於能夠不用重新載入整個版面來更新資料,也就是所謂的Refresh without Reload(輕刷新)
• 與服務器之間的溝通,完全是透過Javascript 來實行
• 使用XMLHttpRequest 本身傳送的數據量很小,所以反應會更快,也就讓網絡程式更像一個桌面應用程序(如:webqq)
• AJAX 就是運用Javascript 在后台悄悄幫你去跟服務器要資料,最后再由Javascript 或DOM 來幫你呈現結果,因為所有動作都是由Javascript 代勞,所以省去了網頁重載的麻煩,使用者也感受不到等待的痛苦
XMLHttpRequest對象
• Ajax應用程序的核心就是它。
• XMLHttpRequest對象在IE瀏覽器和非IE瀏覽器中創建的方法不同。
• function createXHR(){
var request;
if(XMLHttpRequest){
request=new XMLHttpRequest();//非ie瀏覽器
}else{
request =new ActiveXObject("Microsoft.XMLHTTP");//ie瀏覽器
}
return request;
}
• 簡而言之:它可以異步從服務器端獲取txt或者xml數據 json(json主流)
異步請求基本步驟
按照下面模式,XMLHttpRequest對象:
• 創建對象; - new (叫助手過來)
• 創建請求; - open (告訴他要去做的事情)
• 注冊事件; - onreadystatechange(注冊狀態改變執行的事件)
• 發送請求; - send (去吧)
創建XMLHttpRequest對象
• 一、先來創建XMLHttpRequest對象
• 在IE、Firefox、safari和Opera中創建該對象的JavaScript代碼為:
var xhr = new XMLHttpRequest();
• 在IE5/6中代碼為:
var xmlRequest = new ActiveXObject(“Microsoft.XMLHTTP”);
注意,JavaScript區分大小寫。
設置異步對象參數並發送請求
• 二、為XMLHttpRequest對象設置請求參數
1.GET方式
1.1設置參數第一個參數 傳遞方式 第二個參數請求的頁面 第三個參數 true異步 false同步
xhr.open("GET", "GetAreasByAjax.ashx?isAjax=1", true);
1.2GET方式請求可以設置瀏覽器不使用緩存
xhr.setRequestHeader("If-Modified-Since", "0");
或者 xhr.open("GET", "GetAreasByAjax.ashx?_="+Math.random(), true);
1.3發送: xhr.send(null);//GET方式
2.POST方式:
1.1設置參數:xhr.open("POST", "GetAreasByAjax.aspx", true);
1.2添加請求頭:xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");(post方式一定要加)
1.3發送:xhr.send("isAjax=1&na=123");//POST方式
設置回調函數
異步使用XMLHttpRequest對象
異步使用XMLHttpRequest對象時,必須使用:onreadystatechange事件。
使用模式應該是:
• 創建該對象;-new
• 打開請求;-open
• 設置readystatechange事件觸發一個回調函數;
• 發送請求;-send
注:在回調函數中檢查readyState屬性,看數據是否准備就緒(是否等於4)。
• 如果沒有准備好,隔一段時間再次檢查。因為數據沒有下載完時,我們無法使用它的屬性和方法。
• 如果已經准備好,就繼續往下執行;
編寫回調函數
1.在xhr.send之前添加設置回調函數代碼:
xhr.onreadystatechange = watching;
2.回調函數
function watching() {
if (xhr.readyState == 4) {//請求狀態
if (xhr.status == 200) {//服務器返回的狀態碼
var msg = xhr.responseText; //服務器返回的字符串
} else alert("服務器錯誤!" + ajaxH.status);
}
}
異步對象readyState屬性
• readyState屬性
readyState屬性指出了XMLHttpRequest對象在發送/接收數據過程中所處的幾個狀態。XMLHttpRequest對象會經歷5種不同的狀態。
• 0:未初始化。new完后;
• 1:已打開。對象已經創建並初始化,但還未調用send方法
• 2:已發送。已經調用send 方法,但該對象正在等待狀態碼和頭的返回;
• 3:正在接收。已經接收了部分數據,但還不能使用該對象的屬性和方法,因為狀態和響應頭不完整;
• 4:已加載。所有數據接收完畢
XMLHttpRequest常用方法
XMLHttpRequest常用屬性
Json--B/S結構數據傳遞格式
- AJAX傳遞復雜數據如果自己進行格式定義的話會經歷組裝、解析的過程,因此AJAX中有一個事實上的數據傳輸標准JSon。Json(是一個標准,就像 XML一樣,Json規定了對象以什么樣的格式保存為一個字符串)將復雜對象序列化為一個字符串,在瀏覽器端再將字符串反序列化為JavaScript可以讀取的對象。看一下Json的格式。Json被幾乎所有語言支持。var json=[{"a":"1","name":"sun"}];
- C#中將.Net對象序列化為Json字符串的方法:JavaScriptSerializer().Serialize(p),JavaScriptSerializer在System.Web.Extensions.dll中,是.Net3.x中新增的類。
完整:System.Web.Script.Serialization.JavaScriptSerializer
//ajax 請求常見問題
1、請求的路徑中不能包含中
2、不讓get請求讀取瀏覽器緩沖
1) url的?后設置隨機數
2) 在請求頭中添加xhr.setRequestHeader("If-Modified-Since", "0");
3、url傳參 如果內容中有中文,應該進行url編碼
4、區分xhr.readyState和xhr.status
5、區分大小寫
上面這些材料是之前,從網絡收集到的簡單易懂,就收藏在本地筆記了,現在拿出來跟大家一起分享,如果這篇文章作者看到,本人卻無抄襲之意,就是為了學習技術。望諒解。
下面是自己根據ajax的原理實現的登錄,驗證碼生成原理來操作,本案例是將密碼和用戶名記入session了,也是為了記住一個知識點,在一本處理程序中若要使用session必須實現System.Web.SessionState命名空間下的IRequiresSessionState接口。廢話不多說,上demo
Login.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 type="text/javascript"> var xhr = createXHR(); function createXHR() { var request; //非IE瀏覽器創建Xmlxhr對象 if (XMLHttpRequest) { request = new XMLHttpRequest(); } else { //IE瀏覽器創建Xmlxhr對象 request = new ActiveXObject("Microsoft.XMLHTTP"); } return request; }; window.onload = function () { document.getElementById("btnLogin").onclick = function () { var name = document.getElementById("uid").value; var pwd = document.getElementById("pwd").value; var webCode = document.getElementById("webCode").value; var data = "n=" + name + "&p=" + pwd + "&c=" + webCode; xhr.open("POST", "Login.ashx", true); //在post的時候一定加上header xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { var msg = xhr.responseText; if (msg == 1) { alert('登錄成功'); } else if (msg == 2) { alert('驗證碼輸入錯誤'); } else { alert('用戶名或者密碼錯誤'); } } } }; xhr.send(data); }; document.getElementById("imgCode").onclick = function () { var ran = Math.random(); //請求地址加上隨機數參數,目的就是為了讓每次請求的地址不同,不讓驗證碼緩存 xhr.open("GET", "MakeIdentityingCode.ashx?_r=" + ran, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { document.getElementById("imgCode").src = "MakeIdentityingCode.ashx?_r=" + ran; } } }; xhr.send(null); }; }; </script> </head> <body> <table border="0" cellpadding="0" cellspacing="0" style="width: 350px"> <tr> <td> 用戶名: </td> <td> <input type="text" id="uid" value="" /> </td> </tr> <tr> <td> 密碼: </td> <td> <input type="text" id="pwd" value="" /> </td> </tr> <tr> <td> 驗證碼: </td> <td> <input type="text" id="webCode" /><img alt="驗證碼" style="cursor: pointer;" id="imgCode" title="驗證碼" src="MakeIdentityingCode.ashx" height="23px" width="80px" /> </td> </tr> <tr> <td colspan="2" align="center"> <input type="button" value="登錄" id="btnLogin" /><input type="button" id="btnCancel" value="取消" /> </td> </tr> </table> </body> </html>
Login.ashx一般處理程序頁
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; namespace IdentifyingCode { /// <summary> /// Login 的摘要說明 在一般處理程序中若要操作session 則一定要實現IRequiresSessionState接口,否則會報錯 /// </summary> public class Login : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string userName = context.Request.Form["n"]; string userPwd = context.Request.Form["p"]; string code = context.Request.Form["c"]; if (code != context.Session["code"].ToString()) { context.Response.Write("2"); context.Response.End(); } if (userName == "admin" && userPwd == "admin") { context.Response.Write("1"); } else { context.Response.Write("3"); } } public bool IsReusable { get { return false; } } } }
IdentifyingCode.ashx生成驗證碼一般處理程序
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Drawing; using System.Text; using System.Web.SessionState; namespace IdentifyingCode { /// <summary> /// MakeIdentityingCode 的摘要說明 在一般處理程序中若要操作session 則一定要實現IRequiresSessionState接口,否則會報錯 /// </summary> public class MakeIdentityingCode : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg"; //將驗證碼存入session string sessionCode = CreateRandom(); context.Session["code"] = sessionCode; //畫板 using (Bitmap bitmap = new Bitmap(80, 25)) { //畫筆 using (Graphics g = Graphics.FromImage(bitmap)) { //把畫板填充成紅色(默認是黑色) g.FillRectangle(Brushes.Red, 0, 0, bitmap.Width, bitmap.Height); //填充白色,留兩像素的紅色邊框 g.FillRectangle(Brushes.White, 1, 1, bitmap.Width - 2, bitmap.Height - 2); //將驗證碼寫入 g.DrawString(sessionCode, new Font("楷體", 12), Brushes.Red, new PointF(5, 5)); //保存到輸出流中 bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); } } } /// <summary> /// 生成6位的隨機數 簡單模擬生成的驗證碼 /// </summary> /// <param name="n"></param> /// <returns></returns> private string CreateRandom() { string code = "壹貳叄肆伍陸柒捌玖零"; Random r = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 4; i++) { int index = r.Next(0, 10); sb.Append(code[index]); } return sb.ToString(); } public bool IsReusable { get { return false; } } } }
只是一個簡單的demo為了不讓自己以后忘記,好記性不如爛筆頭!!
下載demo:IdentifyingCode.rar