什麼是ajax javascript
AJAX:」Asynchronous JavaScript and XML」html
中文意思:異步JavaScript和XMLjava
指一種建立交互式網頁應用的網頁開發技術。web
不是指一種單一的技術,而是有機地利用了一系列相關的技術:ajax
簡單理解爲:JavaScript + XMLHttpRequest + CSS +服務器端 的集合json
普通的網頁請求回執過程(請求響應模式 同步模式)瀏覽器
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對象
• 1、先來建立XMLHttpRequest對象
• 在IE、Firefox、safari和Opera中建立該對象的JavaScript代碼爲:
var xhr = new XMLHttpRequest();
• 在IE5/6中代碼爲:
var xmlRequest = new ActiveXObject(「Microsoft.XMLHTTP」);
注意,JavaScript區分大小寫。
設置異步對象參數併發送請求
• 2、爲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 請求常見問題
一、請求的路徑中不能包含中
二、不讓get請求讀取瀏覽器緩衝
1) url的?後設置隨機數
2) 在請求頭中添加xhr.setRequestHeader("If-Modified-Since", "0");
三、url傳參 若是內容中有中文,應該進行url編碼
四、區分xhr.readyState和xhr.status
五、區分大小寫
上面這些材料是以前,從網絡收集到的簡單易懂,就收藏在本地筆記了,如今拿出來跟你們一塊兒分享,若是這篇文章做者看到,本人卻無抄襲之意,就是爲了學習技術。望諒解。
下面是本身根據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