Ajax(Asynchronous JavaScript and XML)表示異步的js與xml。
有別於傳統web的同步開發方式。
原理:通過XMLHttpRequest對象向服務器發送異步請求,從服務器獲得數據,然后使用js操作DOM更新數據。
該對象是ajax的核心機制,他是在IE5中首先引入的,是一種支持異步請求的技術。
通過ajax可以及時的向服務器提出請求和處理響應,而不阻塞用戶,達到無刷新更新部分頁面的效果。
XMLHttpRequest這個對象的屬性有:
onreadystatechange 每次狀態改變所觸發事件的事件處理程序;
responseText 從服務器進程返回數據的字符串形式;
responseXML 從服務器進程返回的DOM兼容的文檔數據對象;
status 從服務器返回的數字代碼,常見的200(客戶端請求成功,已就緒)和404(請求資源不存在)
statusText 伴隨狀態碼的字符串信息 (eg:200 OK)
readyState 對象狀態值
0(未初始化狀態)對象已建立或已被abort()方法重置,尚未調用open方法。
1(初始化狀態)open()方法已經調用,但是send()方法為調用。請求還沒有被發送。
2(發送數據)send()方法法以調用,HTTP請求已發送到Web服務器。未接收到響應。
3(數據傳送中)所有響應頭部都已經接收到。響應體開始接受但未完成。
4(完成加載)HTTP響應已經完全接收。
ajax({ url: "./TestXHR.aspx", //請求地址 type: "POST", //請求方式 data: { name: "super", age: 20 }, //請求參數 dataType: "json", success: function (response, xml) { // 此處放成功后執行的代碼 }, error: function (status) { // 此處放失敗后執行的代碼 } });
開始封裝
function ajax(options) { options = options || {}; options.type = (options.type || "GET").toUpperCase(); options.dataType = options.dataType || "json"; var params = formatParams(options.data); var xhr; //創建 - 第一步 if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if(window.ActiveObject) { //IE6及以下 xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //連接 和 發送 - 第二步 if (options.type == "GET") { xhr.open("GET", options.url + "?" + params, true); xhr.send(null); } else if (options.type == "POST") { xhr.open("POST", options.url, true); //設置表單提交時的內容類型 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(params); } //接收 - 第三步 xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status >= 200 && status < 300 || status == 304) { options.success && options.success(xhr.responseText, xhr.responseXML); } else { options.error && options.error(status); } } } } //格式化參數 function formatParams(data) { var arr = []; for (var name in data) { arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name])); } arr.push(("v=" + Math.random()).replace(".")); return arr.join("&"); }