ajax這種常見的開發模式已經遍及咱們平常的開發之中了,ajax本質仍是採用一種輪詢的模式,就是隔一段時間去發送一次http請求,獲取數據,而後顯示在頁面之上,固然,ajax比起新興的WebScoket確定是差了一截,WebScoket基於握手協議,是一種全雙工的通訊。javascript
目前,不少javascript庫都實現了對ajax完善的支持,像jQuery, Ext, Mootools, prototype等。平時是否是就簡單的調用一下$.ajax()或者$.post()就輕鬆的實習了一次ajax請求了呢?若是你過於依賴jQuery等類庫的話,你可能會忽略ajax的原生實現。下面我來談談ajax的原生實現。java
ajax中的核心對象是XMLHttpRequest。像Firefox、 chrome、 opera、 safari等瀏覽器能夠直接經過new XMLHttpRequest()建立,IE6及IE6如下不支持這種方式建立,可是能夠經過new ActiveXObject()建立。常見的HTTP狀態碼中,200表示請求已經發送成功,readyState一共有5種狀態,0表示未鏈接,1表示打開鏈接,2表示發送請求,3表示交互,4表示完成交互並接手響應。瞭解了這些預備知識,咱們就能夠實現一個XHR工廠了。ajax
/** * XHR Factory, use simple factory patten * It handle ajax create, request, send and etc * Written by liufeng cheng * update date: 2014/7/10 * call example: window.onload = function(){ var xhrFactory = new XhrFactory(); var callback = { success:function(responseText,responseXML){alert("Success:" + responseXML);}, failure:function(statusCode){alert("Failure" + statusCode);} }; myHandler.request('GET','innerHTML.xml',callback); }; */ var XhrFactory = function(){}; XhrFactory.prototype = { //ajax create,request,send and etc request:function(method,url,callback,postVars){ var xhr = this.createXhrObject(); xhr.onreadystatechange = function(){ if(xhr.readyState != 4) return; (xhr.status == 200) ? callback.success(eval("(" + xhr.responseText + ")"), xhr.responseXML): callback.failure(xhr.status); }; xhr.open(method,url,true); if(method != "POST") postVars = null; xhr.send(postVars); }, // return a xhr object in different case createXhrObject:function(){ var methods = [ function(){return new XMLHttpRequest();}, function(){return new ActiveXObject('Msxml2.XMLHttp');}, function(){return new ActiveXObject('Microsoft.XMLHttp');} ]; for(var i = 0; i < 3; i++){ try{ methods[i](); }catch(e){ continue; } this.createXhrObject = methods[i](); return methods[i](); } throw new Error("Error!"); } }