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

仿jquery里的最基本的ajax功能
这个只是最基本的,防止我们总是写无效的代码
代码如下:
function getAjaxRequest() {
	var request = false;
	try {
		request = new XMLHttpRequest();
	} catch (IE) {
		try {
			request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
			try {
				request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
				request = false;
			}
		}
	}
	return request;
}

/**
 * 构建建议的ajax参数
 * options{url:"",data,dataType,callback
 * @param options
 */
function Ajax(options)
{
	var request = getAjaxRequest();
	var url     = options.url;
	var data    = null || options.data;
	var dataType = (options.dataType || 'GET').toLocaleUpperCase() == 'POST'?'POST':'GET';
	
	var callback = options.callback;
	//回调函数
	var facade   = function(callback){
		if (request.readyState == 4) {
			if (request.status == 200) 
			{
					var responseText = request.responseText;
					callback && callback(responseText);
			}
		}
		
	};
	try{
		request.open(dataType,url,true);
		if(dataType == "POST")
			request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;"); 
		request.onreadystatechange = function(){
			facade(callback);
		};
		request.send(data);
	}catch(e)
	{
		throw e;
		return ;
	}
	
}