function ajax (options) {
const {
url,
method,
async,
data,
timetout
} = options
const xhr = new XMLHttpRequest()
if (timetout) {
xhr.timeout = timetout
}
return Promise((resolve, reject) => {
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
resolve(xhr.responseText)
} else {
reject()
}
}
}
xhr.onerror = err => reject(err)
xhr.ontimeout = () => reject('timeout')
let _params = []
let encodeData = ''
if (data instanceof Object) {
for (let key in data) {
_params.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
}
encodeData = _params.join('&')
}
if (method === 'get') {
const index = url.indexOf('?')
if (index === -1) {
url += '?'
} else if (index !== url.length-1) {
url += '&'
}
url += encodeData
}
xhr.open(method, url, async)
if (method === 'get') {
xhr.send(null)
} else {
xhr.setRequestHeader({
'content-type': 'application/x-www-form-urlencoded'
})
xhr.send(encodeData)
}
})
}