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

优雅的ajax封转
封装:
var MonitorAjax = function() {
	this.XHR = function() {
		var xmlHttpRequest;
		if(window.XMLHttpRequest) {
			xmlHttpRequest = new XMLHttpRequest();
		} else if(window.ActiveXObject) {
			try {
				xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e1) {
				try {
					xmlHttpRequest = new ActiveXObject("MSXML2.XMLHTTP");
				} catch(e2) {
					try {
						xmlHttpRequest = new ActiveXObject("MSXML3.XMLHTTP");
					} catch(e3) {
						alert('创建异步通信对象失败,这是因为浏览器不支持引起的');
					}
				}
			}
		} else {
			alert("貌似您的浏览器不支持异步通信,部分功能无法正常运行,请切换浏览器,如:IE浏览器");
		}
		return xmlHttpRequest;
	}();
	this.request = function(url,transferType,data,callbackFn) {
		this.XHR.open(transferType,url,true);
		this.XHR.onreadystatechange = function() {
			if(this.readyState == 4) {
				if(this.status == 200) {
					callbackFn(this.responseText);
				}
			}
		};
		if(transferType == "POST" || transferType == "post") {
			this.XHR.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
		}
		this.XHR.send(data);
	};
}



调用:
var monitorAjax = new MonitorAjax();
monitorAjax.request("login.do","post","name=wangfeng",function(result) {
alert(result);
});