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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
| const http = {
ajax: (settings = {}) => { let _s = Object.assign({ url: '', type: 'GET', dataType: 'json', async: true, data: null, headers: {}, timeout: 1000, beforeSend: (xhr) => { }, success: (result, status, xhr) => { }, error: (xhr, status, error) => { }, complete: (xhr, status) => { } }, settings);
if (!_s.url || !_s.type || !_s.dataType || !_s.async) { alert('参数有误'); return; }
let xhr = new XMLHttpRequest();
xhr.addEventListener('loadstart', e => { _s.beforeSend(xhr); }); xhr.addEventListener('load', e => { const status = xhr.status; if ((status >= 200 && status < 300) || status === 304) { let result; if (xhr.responseType === 'text') { result = xhr.responseText; } else if (xhr.responseType === 'document') { result = xhr.responseXML; } else { result = xhr.response; } _s.success(result, status, xhr); } else { _s.error(xhr, status, e); } }); xhr.addEventListener('loadend', e => { _s.complete(xhr, xhr.status); }); xhr.addEventListener('error', e => { _s.error(xhr, xhr.status, e); }); xhr.addEventListener('timeout', e => { _s.error(xhr, 408, e); }); let useUrlParam = false; let sType = _s.type.toUpperCase(); if (sType === 'GET' || sType === 'DELETE') { useUrlParam = true; _s.url += http.getUrlParam(_s.url, _s.data); } xhr.open(_s.type, _s.url, _s.async); xhr.responseType = _s.dataType; for (const key of Object.keys(_s.headers)) { xhr.setRequestHeader(key, _s.headers[key]); } if (_s.async && _s.timeout) { xhr.timeout = _s.timeout; } xhr.send(useUrlParam ? null : http.getQueryData(_s.data)); }, getUrlParam: (url, data) => { if (!data) { return ''; } let paramsStr = data instanceof Object ? http.getQueryString(data) : data; return (url.indexOf('?') !== -1) ? paramsStr : '?' + paramsStr; }, getQueryData: (data) => { if (!data) { return null; } if (typeof data === 'string') { return data; } if (data instanceof FormData) { return data; } return http.getQueryString(data); }, getQueryString: (data) => { let paramsArr = []; if (data instanceof Object) { Object.keys(data).forEach(key => { let val = data[key]; if (val instanceof Date) { } paramsArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); }); } return paramsArr.join('&'); } }
|