国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網(wǎng)站 > WEB開發(fā) > 正文

ajax對象的封裝對回調(diào)函數(shù)的理解

2024-04-27 15:09:10
字體:
供稿:網(wǎng)友

首先看看第一種封裝的方式,這種封裝方式較為簡單,但是在使用的時候方便易容,容易理解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打開連接以及調(diào)用的封裝

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){ //每當(dāng)服務(wù)器的狀態(tài)發(fā)生變化之后,服務(wù)器會向ajax引擎返回一系列的 //數(shù)據(jù),xmlHttp就是返回來的數(shù)據(jù),把這個數(shù)據(jù)作為callback的形參傳遞 callback(xmlHttp.responseText);//xmlHttp.responseText為回調(diào)函數(shù)的實參 } } } //打開連接 xmlHttp.open(method,url,true); //設(shè)置響應(yīng)頭 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //發(fā)送請求 xmlHttp.send("data="+data);}

調(diào)用過程 `window.onload=function(){ ajax(“../AjaxServlet”,”post”,null,function(data){//data為回調(diào)函數(shù)的形參 alert(data); }); };

回調(diào)函數(shù):回調(diào)函數(shù)的思想就是,在封裝ajax對象的時候,callback()這一塊封裝者不知道調(diào)用者需要干什么,誰需要使用,誰就書寫回調(diào)函數(shù),這樣的一種思想

第二種封裝方式

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為回調(diào)函數(shù)的實參 } } } //打開連接 xmlHttp.open(ajaxJSON.method,ajaxJSON.url,true); //設(shè)置響應(yīng)頭 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //發(fā)送請求 xmlHttp.send("data="+ajaxJSON.data);}

調(diào)用方式

window.onload=function(){ ajax2({ url:'../AjaxServlet', method:'post', data:null, callback:function(data){ /** * ajaxJSON.callback(xmlHttp.responseText);//xmlHttp.responseText為回調(diào)函數(shù)的實參 * 這里的this代表this所在的json對象 * ajaxJSON.callback.call(window,xmlHttp.responseText);//xmlHttp.responseText為回調(diào)函數(shù)的實參 * 這里的this代表window */ alert(this); } });};
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 永清县| 罗江县| 新野县| 武安市| 杭州市| 库伦旗| 天津市| 乐业县| 抚松县| 平安县| 抚顺县| 罗田县| 临湘市| 清远市| 商城县| 桂阳县| 大庆市| 怀宁县| 本溪市| 安顺市| 荔波县| 禹州市| 广德县| 肥乡县| 莱西市| 阿合奇县| 屯昌县| 浦江县| 益阳市| 北安市| 泾阳县| 资中县| 平泉县| 锦州市| 平乡县| 九龙县| 九寨沟县| 浦江县| 商城县| 广汉市| 合作市|