更新時間:2021-08-31 10:03:36 來源:動力節點 瀏覽1768次
主要用法:ajax(options).method()[ajax({url:"getData.jsp",method:"POST",data:"userId=123"}).getScript(function(msg){/****/});]; options:一個對象,包含如下選項
url://數據源地址
method://請求方法[POST、HEAD...]
data://要發送給服務器的數據
async://是否是異步請求
timeout://請求超時,默認為十秒
cache://是否從緩存中取數據(如果瀏覽器已緩存)
onSuccess:請求成功并將結果作為參數調用的函數
onError;請求失敗調用的函數
onComplete:請求完成調用的函數,無論成功與否
showStatus;以當前狀態碼為參數調用的函數
type:為本類型,如:txt、js、xml、html
一般情況下url是必需的;其余的可選 ,主要方法:
getText:function(fn)//取文本,請求成功后以獲取的文本為參數調用fn函數
getXML:function(fn)//取XML文本,請求成功后以獲取的XML文檔根對象為參數調用fn函數
getScript:function(fn)//取JavaScript,請求成功后將獲取的代碼用eval執行后的結果為參數調用fn函數
getHTML:function(fn)//取HTML文本,請求成功后以獲取的HTML文本為參數調用fn函數,與getText不同的是文本中的HTML標記可以被正常顯示
oppendTo(obj)://將返回結果添加到指定的DOM對象上,如ajax({url:"get.jsp?data=xyz"}).getHTML().appendTo(document.body)
exe:function(options)//發送和接收請求結果的核心函數,options是一個對象,包含:
onSuccess:請求成功并將結果作為參數調用的函數
onError;請求失敗調用的函數
onComplete:請求完成調用的函數,無論成功與否
showStatus;以當前狀態碼為參數調用的函數
type:為本類型,如:txt、js、xml、html
代碼如下:
(function(wnd,undef){
var doc=wnd.document,OBJ="object",STR="string";
var ajax=function(options){
return new ajax.prototype.init(options);
};
function AjaxError(msg){
this.name="Ajax錯誤";
this.message=msg||"未知錯誤";
}
ajax.prototype={
init:function(option){
this[0]=this.create();//創建Ajax對象
this[1]={
url:option.url||"",//數據源地址
method:option.method||"GET",//請求方法[POST、HEAD...]
data:option.data||null,//要發送給服務器的數據
async:option.async||true,//是否是異步請求
type:option.type||"text",//返回數據后,將數據轉換為指定的類型.(text,js,xml,html)
timeout:option.timeout||10000,//請求超時,默認為十秒
cache:option.cache||false,//是否從緩存中取數據(如果瀏覽器已緩存)
onSuccess:option.onSuccess||function(result){},//請求成功后執行的函數(處理返回結果)
onError:option.onError||function(){},//請求出錯調用的函數
onComplete:option.onComplete||function(){},//請求完成后(無論成功與否)都執行的函數
showStatus:option.showStatus||function(){}//顯示請求狀態
};
fix(this[1]);
return this;
},
create:function(){//創建Ajax對象
if(wnd.XMLHttpRequest==undef){
wnd.XMLHttpRequest=function(){
if(wnd.ActiveXObject){
try{
return new ActiveXObject("Msxml2.XMLHTTP");//IE6
}catch(e){
return new ActiveXObject("Microsoft.XMLHTTP");//IE5
}
}
};
}
return new XMLHttpRequest();
},
stop:function(){
try{
this[0].abort();
}catch(e){
throw new AjaxError(e.message)
}
return this;
},
getText:function(fn){//fn可選
return this.exe({"onSuccess":fn,"type":"text"});
},
getXML:function(fn){
return this.exe({"onSuccess":fn,"type":"xml"});
},
getScript:function(fn){
return this.exe({"onSuccess":fn,"type":"js"});
},
getHTML:function(fn){
return this.exe({"onSuccess":fn,"type":"html"});
},
exe:function(options){
if(options.onSuccess)this[1].onSuccess=options.onSuccess;
if(options.onError)this[1].onError=options.onError;
if(options.onComplete)this[1].onComplete=options.onComplete;
if(options.showStatus)this[1].showStatus=options.showStatus;
if(options.type)this[1].type=options.type;
try{
var isTimeout=false,cur=this;
var timer=setTimeout(function(){
isTimeout=true;
cur.stop();
cur[1].onError(new AjaxError("請求超時"));
},cur[1].timeout);
//私有方法
var open=function(){
try{
cur[0].open(cur[1].method,cur[1].url,cur[1].async);
if(/POST/i.test(cur[1].method)){
cur[0].setRequestHeader("Content-Type","application/x-www-form-urlencoded");//表單編碼
if(cur[0].overrideMimeType)cur[0].setRequestHeader("Connection","close");
}
}catch(e){
throw new AjaxError(e.message);
}
};
var send=function(){
try{
cur[0].send(cur[1].data);
}catch(e){
throw new AjaxError(e.message);
}
};
open();//發起連接
this[0].onreadystatechange=function(){
cur[1].showStatus(cur[0].readyState);
if(cur[0].readyState==4&&!isTimeout){
try{
if(isOK(cur[0])){//成功完成
var t=httpData(cur[0],cur[1].type);
if(cur.to&&cur.to.length>0){
for(var i=0;i<cur.to.length;i++){
if(cur.to[i].type&&cur.to[i].type=="html")
cur.to[i].target.innerHTML+=t;
else cur.to[i].target.appendChild(doc.createTextNode(t));
}
}
cur[1].onSuccess(t);
}
else{
cur[1].onError(new AjaxError("請求未成功完成"));
}
}catch(et){
cur[1].onError(new AjaxError(et.message));
}finally{
cur[1].onComplete();
cur[0]=null;
clearTimeout(timer);
}
}
};
send();
}catch(e){
this[1].onError(new AjaxError(e.message));
}finally{
return this;
}
},
appendTo:function(target){//將返回的結果加到指定的目標[id或DOM對象]
if(!this.to)this.to=[];
this.to.push({
"target":$(target),
"type":this[1].type
});
return this;
}
};//end prototype
ajax.prototype.init.prototype=ajax.prototype;
ajax.parseToQueryString=function(obj){//將數組或對象序列化
if(typeof obj===STR)return obj;
var s=[];
if(obj instanceof Array){//假定為數組
for(var i=0;i<obj.length;i++)
s.push(obj[i].name||i+"="+obj[i]);
}
else{
for(var j in obj) s.push(j+"="+obj[j]);
}
return s.join("&");
} ;
ajax.parseToObject=function(str){//將查詢字符串轉化成對象
if(typeof str==OBJ)return str;
var set={};
str=str.split("&");
var item;
for(var i=0;i<str.length;i++){
if(str[i].indexOf("=")>0){
item=str[i].split("=");
set[item[0]]=item[1];
}
}
return set;
};
var fix=function(p){
if(p.data){
p.data=ajax.parseToQueryString(p.data);
}
if(p.method.toUpperCase()=="GET"&&p.data){
p.url=append(p.url,p.data);
}
if(!p.cache){
p.url=append(p.url,"abkjfjk="+(new Date().getTime())+"jrejhjdd");
}
};
var $=function(id){
return typeof id===OBJ?id:doc.getElementById(id);
};
function isOK(r){
try{
return !r.status&&location.protocol=="file:"
||(r.status>=200&&r.status<300)
||r.status==304
||navigator.userAgent.indexOf("Safari")>=0&&r.status==undef;
}catch(e){}
return false;
}
function httpData(r,type){
var res=type;
if(!res){
var ct=r.getResponseHeader("Content-Type");
if(/xml/i.test(ct)) res="xml";
else if(/JavaScript/i.test(ct))res="js";
else res="";
}
switch(res){
case "xml":
return r.responseXML.documentElement;
case "js":
return eval("("+r.responseText+")");
default:
return r.responseText;
}
}
function append(url,param){
if(url.indexOf("?")<0){
return url+"?"+param;
}
else{
if(/\?$/.test(url)){
return url+param;
}
else{
return url+"&"+param;
}
}
}
wnd.ajax=ajax;
})(window);
以上就是動力節點小編介紹的"超輕量級的Ajax庫",希望對大家有幫助,想了解更多可查看AJAX教程。動力節點在線學習教程,針對沒有任何Java基礎的讀者學習,讓你從入門到精通,主要介紹了一些Java基礎的核心知識,讓同學們更好更方便的學習和了解Java編程,感興趣的同學可以關注一下。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習