AJAX封装数据处理简单操作

数据的封装处理主要展现在JS中,在页面里面引入封装的JS,

“js/ajax.js”

简单封装将get和post方法都写入,get的方法和post的方法依然需要严格区分,包括type类型也要严格书写:

function ajax(method, url, data, success) {  //命名方法
	var xhr = null;
	try {
		xhr = new XMLHttpRequest();
	} catch (e) {
		xhr = new ActiveXObject('Microsoft.XMLHTTP');
	}
	
	if (method == 'get' && data) {
		url += '?' + data;
	}
	
	xhr.open(method,url,true);
	if (method == 'get') {
		xhr.send();
	} else {
		xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
		xhr.send(data);
	}
	
	xhr.onreadystatechange = function() {
		
		if ( xhr.readyState == 4 ) {
			if ( xhr.status == 200 ) {
				success && success(xhr.responseText);
			} else {
				alert('出错了,Err:' + xhr.status);
			}
		}
		
	}
}

然后在页面中使用,使用时只需要引入ajax函数名字即可,然后根据使用get还是post来实现数据处理。

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>AJAX</title>
<style>
.myBtn{
	background:#3498db;
	color:#fff;
	font-size:14px;
	text-align:center;
	width:100px;
	height:36px;
	line-height:34px;
	border:none 0;
	cursor:pointer;
	margin-left:37px;
}
#content{
	
}
#content li{
	list-style:none;
	padding:10px 0;
	white-space:1px;
	border-bottom:1px dashed #999;
}
#content li a{
	color:#000;
	text-decoration:none;
	transition: all 0.3s ease 0s;
}
#content li:hover a{
	color:#246ab8;
	padding-left:10px;
	transition: all 0.3s ease 0s;
}
#content li span{
	color:#777;
}
</style>

<script src="js/ajax.js"></script>
<script>
window.onload = function() {
	
	var oBtn = document.getElementById('btn');
	
	
	oBtn.onclick = function() {
		
		ajax('get','links/getNews.php','',function(data) {  //ajax就是封装的函数名字
			var data = JSON.parse( data ); //字符串转换
				
			var oUl = document.getElementById('content');
			var html = '';
			for (var i=0; i<data.length; i++) {
				html += '<li><a href="">'+data[i].title+'</a> [<span>'+data[i].date+'</span>]</li>';
			}
			oUl.innerHTML = html;
		});
		
	}
}
</script>
</head>

<body>
	<input type="button" value="按钮" id="btn" class="myBtn" />
    <ul id="content"></ul>
</body>
</html>

posted @ 2018-11-09 11:15  沉默的小猴子  阅读(724)  评论(0编辑  收藏  举报