随笔 - 66  文章 - 0 评论 - 614 trackbacks - 3

 

原生js封装

function ajaxRequest(type, url, data, callback, failCallBack, header, dataType) {
	var url_encode = function (str) {
		return encodeURIComponent(str)
			.replace(/ /gi, '+')
			.replace(/~/gi, '%7e')
			.replace(/'/gi, '%26%2339%3b');
	};
	type = String(type || 'GET').toUpperCase();
	if (type == 'GET') {
		var dataStr = typeof (data) === 'string' ? data : '';
		if (typeof (data) === 'object')
			for (var key in data) {
				if (Object.prototype.toString.call((data[key])) == '[object Array]') {
					for (var a = 0; a < data[key].length; a++)
						if (data[key][a] !== undefined) dataStr += key + "=" + url_encode(data[key][a]) + "&";
				}
				if (data[key] !== "" && data[key] !== null) dataStr += key + '=' + url_encode(data[key]) + '&';
			}
		if (dataStr !== '') {
			dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
			url = url + '?' + dataStr;
		}
	}
	var sendData = '';
	var contentType = 'application/x-www-form-urlencoded; charset=utf-8';
	if (type == "FORM") {
		if (typeof (data) === 'string') sendData = data;
		if (typeof (data) === 'object')
			for (var key in data) {
				if (Object.prototype.toString.call((data[key])) == '[object Array]') {
					for (var a = 0; a < data[key].length; a++)
						if (data[key] !== undefined) sendData += key + "=" + url_encode(data[key][a]) + "&";
				}
				else if (data[key] !== "" && data[key] !== null) sendData += key + "=" + url_encode(data[key]) + "&";
			}
	}
	if (type == 'JSON') {
		debugger
		sendData = JSON.stringify(data);
		contentType = "application/json; charset=utf-8";
	}
	if (!failCallBack) failCallBack = console.log;
	var requestObj = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject;
	requestObj.onreadystatechange = () => {
		if (requestObj.readyState == 4) {
			if (requestObj.status == 200) {
				var obj = requestObj.response
				if (String(dataType).toLowerCase() === 'html') return callback(obj);
				if (typeof obj !== 'object') obj = JSON.parse(obj);
				if (obj.code === 0) return callback(obj.data);
				failCallBack(obj);
			} else {
				failCallBack(requestObj)
			}
		}
	};
	requestObj.open(type == 'GET' ? type : 'POST', url, true);
	if (type != 'GET') requestObj.setRequestHeader("Content-type", contentType);
	if (typeof (header) === 'object') for (var key in header) requestObj.setRequestHeader(key, header[key]);
	requestObj.send(sendData || null);
}

 

二次封装,统一处理token,未登录

top.ajaxRequest2 = ajaxRequest; ajaxRequest = function (type, url, data, callback, failCallBack, header, dataType) { if (!header) header = {}; header.token = localStorage.getItem('token'); if (!header.token) delete header.token; top.ajaxRequest2(type, url, data, callback, function (d) { if (d.code === 5009) localStorage.removeItem('token');/*登陆TOKEN失效_请重新登陆*/d.url = type + ' ' + url; console.error(d); if (failCallBack) failCallBack(d); }, header, dataType); };

 

posted on 2018-02-01 14:05 nicye 阅读(...) 评论(...) 编辑 收藏