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
| class Ajax { constructor(config) { this._xhr = null return this.request(config) }
serialize(data) { let params = '' for (const key in data) { params += `${key}=${data[key]}&` } params = '?' + params.substring(0, params.length - 1) return params } config({ baseURL = '', // 前缀 url = '', // 路径 data = {}, // 传入的参数 method = 'get', timeout = 1000 * 5, // 默认等待 5s header = { // 请求头 'Content-Type': 'application/json; charset=UTF-8', }, }) { method = method.toUpperCase() url = baseURL + url const serializeData = this.serialize(data) if (method === 'GET') url = url + serializeData data = (method === 'GET') ? null : serializeData;
const config = { baseURL, url, data, method, timeout, header, }
return config } request(config) { const { url, method, data, timeout, header } = this.config(config)
let xhr if (window.XMLHttpRequest) xhr = new XMLHttpRequest() this._xhr = xhr
return new Promise((resolve, reject) => { if (!xhr) reject('版本不支持')
xhr.onreadystatechange = function() { if (xhr.readyState === 4){ if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) { resolve(xhr.responseText) } else { const error = { status: xhr.status, err: xhr.statusText }; reject(error) } } }
xhr.timeout = timeout xhr.ontimeout = e => { console.error('timeout', e) reject(e) }
xhr.open(method, url, true)
for(const key of Object.keys(header)) { xhr.setRequestHeader(key, header[key]) }
xhr.send(data) }) }
static get(url, params = {}) { const config = { url, method: 'get', data: { ...params } } return this.request(config) }
static post(url, data = {}) { const config = { url, method: 'post', data: { ...data } } return this.request(config) } }
new Ajax()
|