配色: 字号:
ajax
2012-04-16 | 阅:  转:  |  分享 
  
/

主要用法:

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、json



/



(function(wnd,undef){

vardoc=wnd.document,OBJ="object",STR="string";



varajax=function(options){

returnnewajax.prototype.init(options);

};



functionAjaxError(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]);

returnthis;

},



create:function(){//创建Ajax对象

if(wnd.XMLHttpRequest==undef){

wnd.XMLHttpRequest=function(){

if(wnd.ActiveXObject){

try{

returnnewActiveXObject("Msxml2.XMLHTTP");//IE6

}catch(e){

returnnewActiveXObject("Microsoft.XMLHTTP");//IE5

}

}

};

}

returnnewXMLHttpRequest();

},

stop:function(){

try{

this[0].abort();

}catch(e){

thrownewAjaxError(e.message)

}

returnthis;

},

getText:function(fn){//fn可选

returnthis.exe({"onSuccess":fn,"type":"text"});

},

getXML:function(fn){

returnthis.exe({"onSuccess":fn,"type":"xml"});

},

getScript:function(fn){

returnthis.exe({"onSuccess":fn,"type":"js"});

},

getHTML:function(fn){

returnthis.exe({"onSuccess":fn,"type":"html"});

},

getJson:function(fn){

returnthis.exe({"onSuccess":fn,"type":"json"});

},

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{

varisTimeout=false,cur=this;

vartimer=setTimeout(function(){

isTimeout=true;

cur.stop();

cur[1].onError(newAjaxError("请求超时"));

},cur[1].timeout);

//私有方法

varopen=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){

thrownewAjaxError(e.message);

}

};

varsend=function(){

try{

cur[0].send(cur[1].data);

}catch(e){

thrownewAjaxError(e.message);

}

};



open();//发起连接



this[0].onreadystatechange=function(){

cur[1].showStatus(cur[0].readyState);

if(cur[0].readyState==4&&!isTimeout){



try{

if(isOK(cur[0])){//成功完成

vart=httpData(cur[0],cur[1].type);



if(cur.to&&cur.to.length>0){

for(vari=0;i
if(cur.to[i].type&&cur.to[i].type=="html")

cur.to[i].target.innerHTML+=t;

elsecur.to[i].target.appendChild(doc.createTextNode(t));

}

}

cur[1].onSuccess(t);

}

else{

cur[1].onError(newAjaxError("请求未成功完成"));

}



}catch(et){

cur[1].onError(newAjaxError(et.message));

}finally{

cur[1].onComplete();

cur[0]=null;

clearTimeout(timer);

}



}

};



send();



}catch(e){

this[1].onError(newAjaxError(e.message));

}finally{

returnthis;

}



},



appendTo:function(target){//将返回的结果加到指定的目标[id或DOM对象]

if(!this.to)this.to=[];

this.to.push({

"target":$(target),

"type":this[1].type

});

returnthis;

}

};//endprototype

ajax.prototype.init.prototype=ajax.prototype;



ajax.parseToQueryString=function(obj){//将数组或对象序列化

if(typeofobj===STR)returnobj;

vars=[];

if(objinstanceofArray){//假定为数组

for(vari=0;i
s.push(obj[i].name||i+"="+obj[i]);

}

else{

for(varjinobj)s.push(j+"="+obj[j]);

}

returns.join("&");

};



ajax.parseToObject=function(str){//将查询字符串转化成对象

if(typeofstr==OBJ)returnstr;

varset={};

str=str.split("&");

varitem;

for(vari=0;i
if(str[i].indexOf("=")>0){

item=str[i].split("=");

set[item[0]]=item[1];

}

}

returnset;

};



varfix=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="+(newDate().getTime())+"jrejhjdd");

}

};



var$=function(id){

returntypeofid===OBJ?id:doc.getElementById(id);

};



functionisOK(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){}

returnfalse;

}



functionhttpData(r,type){

varres=type;

if(!res){

varct=r.getResponseHeader("Content-Type");

if(/xml/i.test(ct))res="xml";

elseif(/JavaScript/i.test(ct))res="js";

elseres="";

}

switch(res){

case"xml":

returnr.responseXML.documentElement;

case"js":

returneval("("+r.responseText+")");

case"json":

returneval("("+r.responseText+")");

default:

returnr.responseText;

}

}



functionappend(url,param){

if(url.indexOf("?")<0){

returnurl+"?"+param;

}

else{

if(/\?$/.test(url)){

returnurl+param;

}

else{

returnurl+"&"+param;

}

}

}



wnd.ajax=ajax;

})(window);
献花(0)
+1
(本文系Jet编程资料...首藏)