1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| let ajax = (options) => { let extend = (_old, _new) => { let obj = {}; for (let key in _old) { if (!_old.hasOwnProperty(key)) continue; if (!/^(cache|async)$/.test(key)) { obj[key] = _new[key] || _old[key]; } else { obj[key] = key in _new ? _new[key] : _old[key]; } } return obj; };
let hasSearch = (url) => url = url.indexOf('?') > -1 ? '&' : '?';
let encodeObjURI = (data) => { let str = ''; for (let key in data) { str += `${key}=${encodeURIComponent(data[key])}&`; } str = str.slice(0, str.length - 1); return str; }; let _default = { type: 'get', url: null, async: true, cache: true, data: null, dataType: 'text', success: null, error: null };
_default = extend(_default, options); let { type, url, async, cache, data, dataType, success, error } = _default;
let xhr = new XMLHttpRequest(); let regGet = /^(get|delete|head)$/i; let regPost = /^(post|put)$/i;
if (!regGet.test(type) && !regPost.test(type)) return; if (data) { if (Object.prototype.toString.call(data) === '[object Object]') { data = encodeObjURI((data)); } if (regGet.test(type)) { url += `${hasSearch(url)}${data}`; data = null; } } if (regGet.test(type) && cache === false) { url += `${hasSearch(url)}_=${Math.random()}`; } xhr.open(type, url, async);
xhr.onreadystatechange = function () { if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) { let result = xhr.responseText; switch (dataType) { case 'json': result = 'JSON' in window ? JSON.parse(result) : eval('(' + result + ')'); break; case 'xml': result = xhr.responseXML; break; } success && success(result); } if (xhr.readyState === 4 && /^(4|5)\d{2}$/.test(xhr.status)) { error && error(xhr); } };
xhr.send(data); };
|