zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Ajax核心框架函数及例子

AJAX框架 函数 核心 例子
2023-06-13 09:14:12 时间
核心ajax(options)函数中,包含了建立xmlhttprequest,提取数据,判断是否回复成功等,基本满足了日常需求。
复制代码代码如下:

//AgenericfunctionforperformmingAJAXrequests
//Ittakesoneargument,whichisanobjectthatcontainsasetofoptions
//Allofwhichareoutlineinthecomments,below
functionajax(options){
//Loadtheoptionsobjectwithdefaults,ifno
//valueswereprovidedbytheuser
options={
//ThetypeofHTTPRequest
type:options.type||"POST",
//TheURLtherequestwillbemadeto
url:options.url||"",
//Howlongtowaitbeforeconsideringtherequesttobeatimeout
timeout:options.timeout||5000,
//Functionstocallwhentherequestfails,succeeds,
//orcompletes(eitherfailorsucceed)
onComplete:options.onComplete||function(){},
onError:options.onError||function(){},
onSuccess:options.onSuccess||function(){},
//Thedatatypethat"llbereturnedfromtheserver
//thedefaultissimplytodeterminewhatdatawasreturnedfromthe
//andactaccordingly.
data:options.data||""
};
//Createtherequestobject
varxml=newXMLHttpRequest();
//OpentheasynchronousPOSTrequest
//xml.open("GET","/some/url.cgi",true);
xml.open("GET",options.url,true);
//We"regoingtowaitforarequestfor5seconds,beforegivingup
vartimeoutLength=5000;
//Keeptrackofwhentherequesthasbeensuccesfullycompleted
varrequestDone=false;
//Initalizeacallbackwhichwillfire5secondsfromnow,cancelling
//therequest(ifithasnotalreadyoccurred).
setTimeout(function(){
requestDone=true;
},timeoutLength);
//Watchforwhenthestateofthedocumentgetsupdated
xml.onreadystatechange=function(){
//Waituntilthedataisfullyloaded,
//andmakesurethattherequesthasn"talreadytimedout
if(xml.readyState==4&&!requestDone){
//Checktoseeiftherequestwassuccessful
if(httpSuccess(xml)){
//Executethesuccesscallbackwiththedatareturnedfromtheserver
options.onSuccess(httpData(xml,options.type));
//Otherwise,anerroroccurred,soexecutetheerrorcallback
}else{
options.onError();
}
//Callthecompletioncallback
options.onComplete();
//Cleanupafterourselves,toavoidmemoryleaks
xml=null;
}
};
//Establishtheconnectiontotheserver
xml.send();
//DeterminethesuccessoftheHTTPresponse
functionhttpSuccess(r){
try{
//Ifnoserverstatusisprovided,andwe"reactually
//requestingalocalfile,thenitwassuccessful
return!r.status&&location.protocol=="file:"||
//Anystatusinthe200rangeisgood
(r.status>=200&&r.status<300)||
//Successfulifthedocumenthasnotbeenmodified
r.status==304||
//Safarireturnsanemptystatusifthefilehasnotbeenmodified
navigator.userAgent.indexOf("Safari")>=0&&typeofr.status=="undefined";
}catch(e){}
//Ifcheckingthestatusfailed,thenassumethattherequestfailedtoo
returnfalse;
}
//ExtractthecorrectdatafromtheHTTPresponse
functionhttpData(r,type){
//Getthecontent-typeheader
varct=r.getResponseHeader("content-type");
//Ifnodefaulttypewasprovided,determineifsome
//formofXMLwasreturnedfromtheserver
vardata=!type&&ct&&ct.indexOf("xml")>=0;
//GettheXMLDocumentobjectifXMLwasreturnedfrom
//theserver,otherwisereturnthetextcontentsreturnedbytheserver
data=type=="xml"||data?r.responseXML:r.responseText;
//Ifthespecifiedtypeis"script",executethereturnedtext
//responseasifitwasJavaScript
if(type=="script")
eval.call(window,data);
//Returntheresponsedata(eitheranXMLDocumentoratextstring)
returndata;
}
}

在同等目录中,我们可以建立一个rss.xml文件,用这个函数来访问。
rss.xml如下:
复制代码代码如下:

<titles>
<title>
缘份
</title>
<title>
月亮
</title>
<title>
缘份月亮
</title>
</titles>

再建立一个html文档,调用它,就能看到rss.xml中的内容就能被访问到。
整体看看,其实真的比较简洁和简单。不仅是能访问xml格式文件,html,.js格式的文件都可以调用的;
这些都可以在本地建立对应的文件,进行调用,都可以实现。