首先看看第一種封裝的方式,這種封裝方式較為簡單,但是在使用的時候方便易容,容易理解Ajax的深層次的原理
1獲取ajax對象
function ajaxFunction(){ var xmlHttp; try{ // Firefox, Opera 8.0+, Safari xmlhttp=new XMLHttPRequest(); } catch (e){ try{// Internet Explorer xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){} } } return xmlHttp; }2 ajax打開連接以及調用的封裝
function ajax(url,method,data,callback){ //獲取xmphttpRquest對象 var xmlHttp=ajaxFunction(); //事件處理程序 xmlHttp.onreadystatechange=function(){ //alert(xmlHttp.readyState); //alert(xmlHttp.status) if(xmlHttp.readyState==4){ if(xmlHttp.status==200||xmlHttp.status==304){ //每當服務器的狀態發生變化之后,服務器會向ajax引擎返回一系列的 //數據,xmlHttp就是返回來的數據,把這個數據作為callback的形參傳遞 callback(xmlHttp.responseText);//xmlHttp.responseText為回調函數的實參 } } } //打開連接 xmlHttp.open(method,url,true); //設置響應頭 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //發送請求 xmlHttp.send("data="+data);}調用過程 `window.onload=function(){ ajax(“../AjaxServlet”,”post”,null,function(data){//data為回調函數的形參 alert(data); }); };
回調函數:回調函數的思想就是,在封裝ajax對象的時候,callback()這一塊封裝者不知道調用者需要干什么,誰需要使用,誰就書寫回調函數,這樣的一種思想
第二種封裝方式
function ajax2(ajaxJSON){ //獲取xmphttpRquest對象 var xmlHttp=ajaxFunction(); //事件處理程序 xmlHttp.onreadystatechange=function(){ //alert(xmlHttp.readyState); //alert(xmlHttp.status) if(xmlHttp.readyState==4){ if(xmlHttp.status==200||xmlHttp.status==304){ ajaxJSON.callback.call(window,xmlHttp.responseText);//xmlHttp.responseText為回調函數的實參 } } } //打開連接 xmlHttp.open(ajaxJSON.method,ajaxJSON.url,true); //設置響應頭 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //發送請求 xmlHttp.send("data="+ajaxJSON.data);}調用方式
window.onload=function(){ ajax2({ url:'../AjaxServlet', method:'post', data:null, callback:function(data){ /** * ajaxJSON.callback(xmlHttp.responseText);//xmlHttp.responseText為回調函數的實參 * 這里的this代表this所在的json對象 * ajaxJSON.callback.call(window,xmlHttp.responseText);//xmlHttp.responseText為回調函數的實參 * 這里的this代表window */ alert(this); } });};新聞熱點
疑難解答