日期:2014-05-16  浏览次数:20746 次

定制了一个仿jquery的ajax函数

ajax习惯了jquery的ajax函数,但不方便引入jquery。只好自己造轮子。以下是代码:

?

?

function ajax(s)
{
	var def={
		type:"GET",
		cache:false,
		url: location.href,
		contentType: "application/x-www-form-urlencoded",
		async: true,
		data:undefined,
		success:undefined,
		beforeSend:undefined,
		//processing:undefined,
		complete:undefined,
		error:undefined
	};

	for(var k in def){
		if (s[k]==undefined)s[k]=def[k];
	}

	if (s.data!=undefined) s.data=getUrlParam(s.data) ;  
	if (s.type =="GET" && s.data!=undefined) s.url +="?"+  (s.cache? "":"r="+(new Date()).getTime()) +"&" +s.data;
	//alert(s.url);
	var xhr =undefined;
	try{
		xhr = new XMLHttpRequest();
		xhr.open(s.type, s.url, s.async);
		xhr.onreadystatechange = function() { 
			switch(this.readyState){
				case 1: 
					if (s.beforeSend!=undefined)s.beforeSend(this); 
					break;
				/*case 3:  if (s.processing!=null)s.processing(this);  break;*/
				case 4: 
					if (this.status==200 && s.success!=undefined) s.success(this.responseText);
					if (s.complete!=null) s.complete(this); 
					break;
			}
		};
		xhr.send( s.type !="GET"? s.data:null);

	}catch(err){
		if (s.error!=undefined)s.error(err.description);
	}finally{
		xhr=null;
	}
}

function getUrlParam ( o ){
  var s = [ ];
  for ( var k in o )
	s[ s.length ] =k + '=' + o[k]; //encodeURIComponent(k) + '=' + encodeURIComponent(o[k]);
  return s.join("&").replace(/%20/g, "+");
}

?