AJAX 是一種用于創(chuàng)建快速動(dòng)態(tài)網(wǎng)頁(yè)的技術(shù)。通過(guò)在后臺(tái)與服務(wù)器進(jìn)行少量數(shù)據(jù)交換,AJAX 可以使網(wǎng)頁(yè)實(shí)現(xiàn)異步更新。這意味著可以在不重新加載整個(gè)網(wǎng)頁(yè)的情況下,對(duì)網(wǎng)頁(yè)的某部分進(jìn)行更新。
在js中使用ajax請(qǐng)求一般包含三個(gè)步驟:
- 1、創(chuàng)建XMLHttp對(duì)象
- 2、發(fā)送請(qǐng)求:包括打開(kāi)鏈接、發(fā)送請(qǐng)求
- 3、處理響應(yīng)
在不使用任何的js框架的情況下,要想使用ajax,可能需要向下面一樣進(jìn)行代碼的編寫(xiě)
<span style="font-size:14px;">var xmlHttp = xmlHttpCreate();//創(chuàng)建對(duì)象 xmlHttp.onreadystatechange = function(){//響應(yīng)處理 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);//打開(kāi)鏈接 xmlHttp.send(null);//發(fā)送請(qǐng)求 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>
如果在比較復(fù)雜的業(yè)務(wù)邏輯里面使用這種ajax請(qǐng)求,會(huì)使得代碼很臃腫,不方便重用,并且可以看到,可能在服務(wù)器響應(yīng)成功后要處理一個(gè)業(yè)務(wù)邏輯操作,這個(gè)時(shí)候不得不把操作寫(xiě)在onreadystatechage方法里面。
為了方便代碼的重用我們可以做出如下處理;
- 1、服務(wù)器響應(yīng)成功后,要處理的業(yè)務(wù)邏輯交給開(kāi)發(fā)人員自己處理
- 2、對(duì)請(qǐng)求進(jìn)行面向?qū)ο蟮姆庋b
處理之后看起來(lái)應(yīng)該像下面這個(gè)樣子:
<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("開(kāi)始請(qǐng)求"); 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; //創(chuàng)建XMLHttp對(duì)象,打開(kāi)鏈接、請(qǐng)求、響應(yīng) 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); } };
上述代碼實(shí)現(xiàn)了類似jquery中的ajax操作,希望對(duì)大家的學(xué)習(xí)有所幫助。