闭包封装ajax

1、参考druid数据源设计:https://blog.csdn.net/blog_zxb/article/details/97416487

// 定义命名空间方法,自动创建多级变量
var namespace = function(){
	var a = arguments, o = null, i, j, d;
	for (var i = 0; i < a.length; i++) {
		o = window;
		d = a[i].split('.');
		for (var j = 0; j < d.length; j++) {
			o[d[j]] = o[d[j]] || {};
			o = o[d[j]];
		}
	}
	return o;
};

 2、闭包设计ajax(原来的设计:https://blog.csdn.net/blog_zxb/article/details/97407209

myajax.js文件内容如下

// 定义命名空间方法,自动创建多级变量
var namespace = function(){
	var a = arguments, o = null, i, j, d;
	for (var i = 0; i < a.length; i++) {
		o = window;
		d = a[i].split('.');
		for (var j = 0; j < d.length; j++) {
			o[d[j]] = o[d[j]] || {};
			o = o[d[j]];
		}
	}
	return o;
};
namespace('xiao.bing.zhou');
xiao.bing.zhou = (function(){
	
	return {
		ajax: function(opt){
			opt = opt || {};
			var url = opt.url || '';
			var type = opt.type || 'get';
			var data = opt.data || null;
			var dataType = opt.dataType || '';
			var success = opt.success;
			var error = opt.error;
			if(!opt.success){
				console.error('ajax not has success function!');
				return;
			}
			if(!opt.error){
				console.error('ajax not has error function!');
				return;
			}
			var xhr;
			
			if (XMLHttpRequest) {
				xhr = new XMLHttpRequest();
		    }else {
		    	xhr = new ActiveXObject('Microsoft.XMLHTTP');
		    }
			
			xhr.onreadystatechange=function(){
				if(xhr.readyState === 4){
					if(xhr.status === 200){
						var result = xhr.responseText;
						if(dataType === 'json'){
							try{
								result = JSON.parse(result);
							}catch(err){
								console.error(err);
								error(xhr, xhr.statusText, err);
								return;
							}
						}
						success(result);
					}else{
						error(xhr, xhr.statusText);
					}
				}
			}
			xhr.open(type, url, true);
			xhr.send(data);
		}
	}

})();

3、使用(需要引入myajax.js)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="javascript:testMyAjax();">测试myAjax</a>
</body>
<script type="text/javascript" src="myajax.js"></script>
<script type="text/javascript">
function testMyAjax(){

    xiao.bing.zhou.ajax({
		url: location.path + 'alarmAction/testJson',
		type: 'get',
		dataType: 'text',
		success: function(data){
			console.log(data);
			alert(data);
		},
		error: function(xhr,statusText){
			console.log(xhr);
			console.log(statusText);
			alert(xhr);
		}
	});
}
</script>
</html>
发布了53 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/blog_zxb/article/details/97507198