阅读背景:

使用js仿写jquery中$.ajax()方法_baidu_36720706的博客_仿写ajax

来源:互联网 

核心代码:

var Ajax = function(option){
	var _option = {
		xmlhttp : null,
		type: "GET",
		async: true,
		data: "",
		contentType: "application/x-www-form-urlencoded",
		dataType: "text", // json
		url: "",
		success: function(status, response){},
		complete: function(status, response){},
		error: function(e){console.error(e);},
		timeout: function(e){console.error(e);}
	}
	
	for( key in option){
		_option[key] = option[key];
	}
	
	var xmlhttp = (function(){
		if (window.XMLHttpRequest){// code for all new browsers
			return new XMLHttpRequest();
		}else if (window.ActiveXObject){// code for IE5 and IE6
			return new ActiveXObject("Microsoft.XMLHTTP");
		}
	})();
	if(xmlhttp != null) {
		xmlhttp.open(_option.type, _option.url, _option.async);
		xmlhttp.responseType = _option.dataType;
		xmlhttp.setRequestHeader("content-type", _option.contentType);
		xmlhttp.ontimeout = function(e) {
			_option.timeout(e);
		};
		xmlhttp.onerror = function(e) {
			_option.error(e);
		};
		
		xmlhttp.onreadystatechange = function(){
			if (xmlhttp.readyState == 4){
				if (xmlhttp.status == 200) {
					_option.success(xmlhttp.status, xmlhttp.response);
				}
				_option.complete(xmlhttp.status, xmlhttp.response);
			}
		}
		
		xmlhttp.send(_option.data);
	} else {
		console.error("Your browser does not support XMLHTTP.");
	}
}var Ajax = function(option){
	var _o



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: