简单封装原生的ajax

1、定义myajax对象 

window.myAjax=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;
	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);
	
}

2、使用myajax

<!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(){
	myAjax({
		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>

3、效果图

 

发布了53 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

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