一、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);
以上就是本文的全部內容,希望對大家的學習有所幫助。