XMLHttpRequest 简单封装

当开发简单页面的时候,不需要引入任何js库,这时需要封装一个用到 XMLHttpRequest 对象的好用的接口请求。

simple 封装如下

ajaxRequest({
	url: '',
	method: 'POST',
	type: 'json',
	data: {},
	success: function(res) {
		console.log(res)
	},
	erro: function(err) {
		console.log(err)
	} 
})
function ajaxRequest(option) {
	// 1. 首先简单验证传进来的参数是否合法
	if(Object.prototype.toString.call(option) !== '[object, Object]') return undefined;
	// 2. 对参数容错处理
	option.method = option.method ? option.method.toUpperCase() : 'GET'; // 默认 GET 请求
	option.data = option.data || {};
	option.type = option.type || 'json';
	
	// 3. 如果是 GET 请求,需要处理 data 里的数据并且以一定的规则拼接到 url 后
	var formData = [];
	for(key in option.data) {  // Object.keys.forEach
		formData.push(''.concat(key, '=', option.data[key]))
	}
	option.data = formData.join('&') //eg: a=b&c=d&e=f
	if(option.method === 'GET' && formData.lenght > 0) { // 注意,option.data 为空对象的时候,就不用拼接参数了
		// 连接本身有参数的时候拼接 &option.data,如果本身没有参数拼接 ?option.data
		option.url += location.search.length === 0 ? ''.concat('?', option.data) : ''.concat('&', option.data); 
	}
	// 4. 实例化 XMLHttpRequest 对象,并进行一些设置
	var xhr = new XMLHttpRequest();
	xhr.responseType = option.type;
	xhr.withCredentials = false;  //指示是否应使用Cookie或授权标头等凭据进行跨站点访问控制请求。
	// 5. 处理请求回调
	xhr.onreadystatechange = function() {
		if(xhr.readyState === 4) {
			if(xhr.status === 200) {
				if(option.success && typeof option.success === 'function') {
					option.success(xhr.response)
				}
			} else {
				if(option.error && typeof option.error === 'function') {
					option.error(new Error(xhr.statusText))
				}
			}
		}
	}
	xhr.open(option.method, option.url, true); // true 代表是异步请求
	// 6. 如果是 POST 请求,需要设置请求头
	if (option.method === 'POST') {
	  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
	}
	// 7. 发送请求
	xhr.send(option.method === 'POST' ? option.data : null);
}
原文地址:https://www.cnblogs.com/cindycindy/p/13591396.html