ajax封装

encodeURIComponent实现了对一些特殊字符的编码,传到后台需后台解码,可以根据自己的业务只对一些特殊的接口做编码。

post请求头Content-Type一般有json和form两种格式,分别以json和键值对格式传给后端。

function axios({
	url,
	method = 'GET',
	params,
	data = {},
	header,
	success,
	fail,
}) {
	return new Promise((resolve, reject) => {
		method = method.toUpperCase()
		let xhr = new XMLHttpRequest();
		// params拼接到url后面
		if (params) {
			url += "?" + parameter(params);
		}
		xhr.open(method, url, true);
		// 设置请求头
		if (header) {
			for (const key in header) {
				if (key) {
					xhr.setRequestHeader(key, header[key]);
				}
			}
		}
		if (method == "POST") {
			// post有form和json两种格式,根据自己的需要选择,或者不写在header中配置
			xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			// xhr.setRequestHeader("Content-Type", "application/json");
			if (data) {
				xhr.send(parameter(data));
				// xhr.send(JSON.stringify(data));
			} else {
				xhr.send();
			}
		} else {
			xhr.send(null);
		}
		xhr.onreadystatechange = function () {
			if (xhr.readyState !== 4) return
			let {
				status,
				statusText,
			} = xhr
			// status[200,300)直接代表成功
			if (status >= 200 && status < 300) {
				let response = {
					data: JSON.parse(xhr.response),
					status,
					statusText,
				}
				if (success) success(response)
				resolve(response)
			} else {
				let error = new Error("响应出错,状态为:" + status + ",出错原因" + statusText)
				if (fail) fail(error)
				reject(error)
			}
		}
	})
}

function parameter(obj) {
	var arr = [];
	for (var item in obj) {
		arr.push(item + "=" + encodeURIComponent(obj[item]));
	}
	return arr.join("&");
}
// 测试
axios({
	url: 'http://129.28.151.93/api/blog/list',
	header: {
		token: '5e3fd7109ce3d27781b07b92'
	}
}).then(res => {
	console.log(res);
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值