AJAX 是一種用于創建快速動態網頁的技術。通過在后臺與服務器進行少量數據交換,AJAX 可以使網頁實現異步更新。這意味著可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新。
在js中使用ajax請求一般包含三個步驟:
- 1、創建XMLHttp對象
- 2、發送請求:包括打開鏈接、發送請求
- 3、處理響應
在不使用任何的js框架的情況下,要想使用ajax,可能需要向下面一樣進行代碼的編寫
<span style="font-size:14px;">var xmlHttp = xmlHttpCreate();//創建對象 xmlHttp.onreadystatechange = function(){//響應處理 if(xmlHttp.readyState == 4){ console.info("response finish"); if(xmlHttp.status == 200){ console.info("reponse success"); console.info(xmlHttp.responseText); } } } xmlHttp.open("get","TestServlet",true);//打開鏈接 xmlHttp.send(null);//發送請求 function xmlHttpCreate() { var xmlHttp; try { xmlHttp = new XMLHttpRequest;// ff opera } catch (e) { try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// ie } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } return xmlHttp; } console.info(xmlHttpCreate());</span>
如果在比較復雜的業務邏輯里面使用這種ajax請求,會使得代碼很臃腫,不方便重用,并且可以看到,可能在服務器響應成功后要處理一個業務邏輯操作,這個時候不得不把操作寫在onreadystatechage方法里面。
為了方便代碼的重用我們可以做出如下處理;
- 1、服務器響應成功后,要處理的業務邏輯交給開發人員自己處理
- 2、對請求進行面向對象的封裝
處理之后看起來應該像下面這個樣子:
<pre code_snippet_id="342814" snippet_file_name="blog_20140513_2_2489549" name="code" class="javascript">window.onload = function() { document.getElementById("hit").onclick = function() { console.info("開始請求"); ajax.post({ data : 'a=n', url : 'TestServlet', success : function(reponseText) { console.info("success : "+reponseText); }, error : function(reponseText) { console.info("error : "+reponseText); } }); } } var ajax = { xmlHttp : '', url:'', data:'', xmlHttpCreate : function() { var xmlHttp; try { xmlHttp = new XMLHttpRequest;// ff opera } catch (e) { try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// ie } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } return xmlHttp; }, post:function(jsonObj){ ajax.data = jsonObj.data; ajax.url = jsonObj.url; //創建XMLHttp對象,打開鏈接、請求、響應 ajax.xmlHttp = ajax.xmlHttpCreate(); ajax.xmlHttp.open("post",ajax.url,true); ajax.xmlHttp.onreadystatechange = function(){ if(ajax.xmlHttp.readyState == 4){ if(ajax.xmlHttp.status == 200){ jsonObj.success(ajax.xmlHttp.responseText); }else{ jsonObj.error(ajax.xmlHttp.responseText); } } } ajax.xmlHttp.send(ajax.data); } };
上述代碼實現了類似jquery中的ajax操作,希望對大家的學習有所幫助。