講到ajax這個東西,咱們要知道兩個對象XMLHTTPRequest和ActiveXObject ,提供了對 HTTP 協議的徹底的訪問,包括作出 POST 和 HEAD 請求以及普通的 GET 請求的能力。能夠同步或異步返回 Web 服務器的響應,而且能以文本或者一個 DOM 文檔形式返回內容。XMLHTTPRequest基本上算是標準化了,兼容大部分瀏覽器ActiveXObject這玩兒意兒是微軟的東西,因此是爲了兼容IE版本,咱們用的只是它的xmlHTTP功能。web
爲了功能的明確和清晰,咱們把這個ajax代碼分爲5個部分:ajax
1.對象的建立 :瀏覽器
若是捕獲錯誤,則嘗試更老的方法 (Internet Explorer 5.5) :XMLHttp=new ActiveXObject("Microsoft.XMLHTTP")服務器
var xhrFactory = function () { this.init.apply(this, arguments); } xhrFactory.prototype = { init: function () { this.xhr = this.create(); }, create: function () { var xhr = null; try { if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Msxml2.Xmlhttp"); } } catch (err) { xhr = new ActiveXObject("Microsoft.Xmlhttp"); } return xhr; } }
2.onreadystatechange句柄:app
readystate: function (timeout,callback) { this.xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { callback(eval("(" + this.responseText + ")")); } else { setTimeout(function () { this.xhr.abort(); }, !timeout ? 15000 : timeout); } } }
這裏面要說一下readyState和status屬性。異步
readyState : 1.建立MLHTTP對象 2.打開與服務器的鏈接 3 .發送指令 4 等待處理請求結果 。async
status: 200.請求成功 400.請求錯誤。。。還有不少值 ,這裏就不一個個說了。post
timeout參數是請求過時時間 callback參數,回調對返回數據作了處理,轉換成對象。this
3.參數拼接編碼
para: function (data) { var datastr = ""; if (data && Object.prototype.toString.call(data) == "[object Object]") { for (var i in data) { for (var i = 0; i < length; i++) { datastr += i + "=" + data[i] + "&"; } } } return datastr; }
這裏是將傳入的對象參數拼接成字符竄,用於ajax請求時發送參數。
4.Get功能實現:
get: function (url, data, callback, async, timeout) { this.readystate(timeout, callback); var newurl = url; var datastr = this.para(data); newurl = url + "?" + datastr; this.xhr.open("get", newurl, !async ? true : async); this.xhr.send(null); }
get 請求,發送的參數是直接在url上拼接的,而不是在send裏面發送,而post方式參數則是在send裏面發送。
5.Post功能實現
post: function (url, data, callback, async, timeout) { this.readystate(timeout, callback); var newurl = url; var datastr = this.para(data); this.xhr.open("post", newurl, !async ? true : async); this.xhr.setRequestHeader("content-type", "x-www-form-urlencoded"); this.xhr.send(!datastr ? null : datastr); }
post這裏面多了一段代碼:this.xhr.setRequestHeader("content-type", "x-www-form-urlencoded");
這段代碼實際上是說明將整個發送內容做爲一個總體進行編碼,get則是單個參數進行編碼拼接 ,這也是post和get的區別。
調用方式以下 :
var xhr = new xhrFactory(); xhr.post("test.ashx", null, function (data) { alert(data); });