一、Ajax (Asynchronous JavaScript + XML) 能夠像伺服器請求額外的資料而無需卸載頁面,即局部重新整理技術
二、建立一個XHR對象
function createXHR () { if (typeof XMLHttpRequest != "undefined") { return new XMLHttpRequest(); } else if (typeof ActiveXObject != "undefined") { // < Ie7 if (typeof arguments.callee.activeXString != "string") { var version = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"], i, len; for ( i = 0, len = version.length; i < len; i++) { try { new ActiveXObject(version[i]); arguments.callee.activeXString = version[i]; break; } catch (ex) {} } } return new ActiveXObject(arguments.callee.activeXString); } else { throw new Error("No Support For XHR"); } } var xhr = createXHR(); alert(xhr); // [object XMLHttpRequest]
三、用法 注意:本節的執行個體都應用於伺服器端
1.調用open()方法。它接受3 個參數:要發送的請求的類型("get"、"post"等)、請求的URL 和表示是否非同步發送請求的布爾值。
2.要發送請求,調用send()方法,接受一個參數,即要作為請求發送的主體。如果不需要,則為null
3.返回的資料會自動填滿到XHR對象的屬性中。
var xhr = createXHR(); // GET方式同步開啟example.txt檔案 // 同步:javascript代碼會等待伺服器響應後執行 xhr.open("get", "example.txt", false); xhr.send(null); // status代表響應的http狀態 // 200代表ok,304表示緩衝 if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ alert(xhr.responseText); // 返迴響應的文本,123456 } else { alert("Request was unsuccessful: " + xhr.status); }
4.example.text檔案內容為字串: 123456
四、前面的使用的同步的方式,當然不會存在問題,所有我們要挑戰一個非同步方法。
var xhr = createXHR();
// xhr.readyState表示請求/響應的目前狀態,4代表已經接受了全部的響應資料 // 另外只要xhr.readyState的值發生了改變,那麼xhr.onreadystatechange事件就會觸發 xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful: " + xhr.status); } } }; xhr.open("get", "example.txt", true); xhr.send(null);
五、每個HTTP 要求和響應都會帶有相應的頭部資訊
1.預設情況下,在發送XHR 請求的同時,還會發送下列頭部資訊。
①Accept:瀏覽器能夠處理的內容類型。
②Accept-Charset:瀏覽器能夠顯示的字元集。
③Accept-Encoding:瀏覽器能夠處理的壓縮編碼。
④Accept-Language:瀏覽器當前設定的語言。
⑤Connection:瀏覽器與伺服器之間串連的類型。
⑥Cookie:當前版面設定的任何Cookie。
⑦Host:發出請求的頁面所在的域。
⑧Referer:發出請求的頁面的URI。
⑨User-Agent:瀏覽器的使用者代理程式字串。
2.使用setRequestHeader()方法可以設定自訂的要求標頭部資訊。接受兩個參數:頭部欄位的名稱和頭部欄位的值
var xhr = createXHR(); // xhr.readyState表示請求/響應的目前狀態,4代表已經接受了全部的響應資料 // 另外只要xhr.readyState的值發生了改變,那麼xhr.onreadystatechange事件就會觸發 xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful: " + xhr.status); } } }; xhr.open("get", "example.txt", true); // 必須在open()之後調用 xhr.setRequestHeader("name", "zhang"); // 在example.txt的http中可以看到接受的 "name" : "zhang" xhr.send(null);
3.擷取請求的頭部資訊和相應資訊,調用getResponseHeader()方法getAllResponseHeaders()方法
var xhr = createXHR(); // xhr.readyState表示請求/響應的目前狀態,4代表已經接受了全部的響應資料 // 另外只要xhr.readyState的值發生了改變,那麼xhr.onreadystatechange事件就會觸發 xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ // 擷取回應標頭的Content-Type var connection = xhr.getResponseHeader("Content-Type"); // alert(connection); // text/plain // 擷取所有的響應資訊 var all = xhr.getAllResponseHeaders(); alert(all); } else { alert("Request was unsuccessful: " + xhr.status); } } }; xhr.open("get", "example.txt", true); xhr.send(null);
六、GET請求,前面我們已經討論了GET請求的方法,現在我們來擴充一下,為GET請求添加一些參數
/** url : 不帶請求的url name : 請求鍵 value : 請求值 return : 帶請求字串的url */ function addURLParam(url, name, value) { url += (url.indexOf("?") == -1 ? "?" : "&"); url += encodeURIComponent(name) + "=" + encodeURIComponent(value); return url; } var xhr = createXHR(); xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful: " + xhr.status); } } }; var url = "example.txt"; url = addURLParam(url, "name", "zhang"); url = addURLParam(url, "age", "23"); // 請求的url變成了:example.txt?name=zhang&age=23 xhr.open("get", url, true); xhr.send(null);
七、POST請求
1.案例分析:接下來我們共同討論一個以post方法發送請求的ajax應用,即使用者註冊,根據你註冊使用者名稱返回提示。
2.實現步驟
1) 首先要有一個註冊的頁面(當然,這裡很簡陋)ajax.html
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>無標題文檔</title> <style> </style> </head> <body> <form name="myForm" method="post"> 姓名:<input type="text" name="username" /><label id="userLabel">請輸入使用者名稱</label><br/> 密碼:<input type="password" name="password" /><br/> <input type="submit" value="登入" /><br/> </form> <script src="EventUtil.js"></script> <script src="serialize.js"></script> <script src="ajax.js"></script> <script src="ajaxDo.js"></script> </body> </html>
2) 接著當然是javascript部分
①EventUtil.js,這裡只是將事件監聽的部分列出來
var EventUtil = { addEvent : function (element, type, handler) { if (element.addEventListener) { element.addEventListener(type, handler, false); } else if (element.attachEvent) { element.attachEvent("on" + type, handler); } } }
②serialize.js:表單序列化
function serialize(form){ var parts = [], field = null, i, len, j, optLen, option, optValue; for (i=0, len=form.elements.length; i < len; i++){ field = form.elements[i]; switch(field.type){ case "select-one": case "select-multiple": if (field.name.length){ for (j=0, optLen = field.options.length; j < optLen; j++){ option = field.options[j]; if (option.selected){ optValue = ""; if (option.hasAttribute){ optValue = (option.hasAttribute("value") ? option.value : option.text); } else { optValue = (option.attributes["value"].specified ? option.value : option.text); } parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(optValue)); } } } break; case undefined: //欄位集 case "file": //檔案輸入 case "submit": //提交按鈕 case "reset": //重設按鈕 case "button": //自訂按鈕 break; case "radio": //選項按鈕 case "checkbox": //複選框 if (!field.checked){ break; } /* 執行預設操作*/ default: //不包含沒有名字的表單欄位 if (field.name.length){ parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value)); } } } return parts.join("&"); }
③ajax.js,就是上面的那個createXHR()函數,這裡就不羅列了。
④ajaxDo.js,核心檔案,就是我們操作部分,這個名字亂寫的。
var form = document.forms[0]; // 擷取表單 var username = form.elements['username']; // 使用者名稱 var userLabel = document.querySelector("#userLabel"); // 提示標籤 EventUtil.addEvent(username, "blur", function() { var xhr = createXHR(); xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ var text = xhr.responseText; // 當為true時,提示綠色字型 // 當為false時,提示為紅色字型 if(text) { userLabel.style.color = "green"; userLabel.firstChild.data = "恭喜你,使用者名稱可用"; } else { userLabel.style.color = "red"; userLabel.firstChild.data = "對不起,該使用者已存在"; } } else { alert("Request was unsuccessful: " + xhr.status); } } }; // POST請求 xhr.open("post", "dome.php", true); // 提交的內容類型 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 將表單序列化 xhr.send(serialize(form)); });
3.改進部分:大家都看見了,剛才在提交表單時,我們序列化了表單。在XMLHttpRequest 2 級為此定義了FormData 類型,它會自動為我們序列化表單,不需要我們自己寫了。
我們只動部分代碼
// ...此處省略代碼和上面一致 // POST請求 xhr.open("post", "dome.php", true); // 僅僅這裡需要改動,代替之前serialize.js中的函數 xhr.send(new FormData(form));
八、其他部分(瞭解,因為相容性還不夠)
1.逾時設定
xhr.open("get", "example.txt", true); xhr.timeout = 1000; //將逾時設定為1 秒鐘(僅適用於IE8+) xhr.ontimeout = function(){ alert("Request did not return in a second."); }; xhr.send(null);
2.overrideMimeType()方法,針對伺服器返回的類型
var xhr = createXHR(); xhr.open("get", "example.txt", true); xhr.overrideMimeType("text/xml"); // 之前的是text/plain xhr.send(null);
3.進度事件
1.load事件,只要瀏覽器收到伺服器的資訊就觸發
var xhr = createXHR(); xhr.onload = function(){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ alert(xhr.responseText); } else { alert("Request was unsuccessful: " + xhr.status); } }; xhr.open("get", "example.txt", true); xhr.send(null);
2.progress事件,瀏覽器接收新資料期間周期性地觸發
var xhr = createXHR(); xhr.onprogress = function(event){ var divStatus = document.getElementById("status"); // 計算從響應中已經接收到的資料的百分比 if (event.lengthComputable){ divStatus.innerHTML = "Received " + event.position + " of " + event.totalSize +" bytes"; } }; xhr.open("get", "altevents.php", true); xhr.send(null);
以上就是本文的全部內容,希望對大家的學習有所協助。