【前端学习笔记04】JavaScript数据通信Ajax方法封装

//Ajax 方法封装 
//设置数据格式
function setData(data){
	if(!data){
		return '';
	}
	else{
		var arr = [];
		for(k in data){
			if(!data.hasOwnProperty(k)) continue;
			if(typeof data[k] == 'function') continue;
			var value = data[k].toString();
			var key = encodeURIComponent(k);
			value = encodeURIComponent(value);
			arr.push(key + '=' + value);
		}
		return arr.join('&');
	}
}
//get()方法封装
function get(url,obj,callback){
	var xhr = null;
	if(window.XMLHttpRequest){
		xhr = new XMLHttpRequest();
	}
	else{
		xhr = new ActiveXObject('Microsoft.XMLHTTP');
	}
	url = url + '?'+ setData(obj);
	xhr.open('get',url,true);
	xhr.onreadystatechange = function(){
		if(xhr.readyState == 4){
			if(xhr.status == 200){
				callback(xhr.responseText);
			}
		}
	}
	xhr.send(null);
}

//post()方法封装
function post(url,obj,callback){
	var xhr = null;
	var postBody = setData(obj);
	if(window.XMLHttpRequest){
		xhr = new XMLHttpRequest();
	}
	else{
		xhr = new ActiveXObject('Microsoft.XMLHTTP');
	}
	xhr.open('post',url,true);
	xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
	xhr.onreadystatechange = function(){
		if(xhr.readyState == 4){
			if(xhr.status == 200){
				callback(xhr.responseText);
			}
		}
	}
	xhr.send(postBody);
}
原文地址:https://www.cnblogs.com/zachary93/p/6054481.html