//調用函數 ajax({ url: 'your request url', method: 'get', async: true, timeout: 1000, data: { test: 1, aaa: 2 } }).then( res => console.log('請求成功: ' + res), err => console.log('請求失敗: ' + err) ) //重點。。。函數封裝function ajax (options) { let url = options.url const method = options.method.toLocaleLowerCase() || 'get' const async = options.async != false // default is true const data = options.data const xhr = new XMLHttpRequest() if (options.timeout && options.timeout > 0) { xhr.timeout = options.timeout } return new Promise ( (resolve, reject) => { xhr.ontimeout = () => reject && reject('請求逾時') xhr.onreadystatechange = () => { if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) { resolve && resolve(xhr.responseText) } else { reject && reject() } } } xhr.onerror = err => reject && reject(err) let paramArr = [] let encodeData if (data instanceof Object) { for (let key in data) { // 參數拼接需要通過 encodeURIComponent 進行編碼 paramArr.push( encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) ) } encodeData = paramArr.join('&') } if (method === 'get') { // 檢測 url 中是否已存在 ? 及其位置 const index = url.indexOf('?') if (index === -1) url += '?' else if (index !== url.length -1) url += '&' // 拼接 url url += encodeData } xhr.open(method, url, async) if (method === 'get') xhr.send(null) else { // post 方式需要佈建要求頭 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8') xhr.send(encodeData) } } ) }