// 封装接口请求方法
const getJSON = function(data) {
const promise = new Promise(function(resolve, reject) {
const handler = function() {
if (this.readyState !== 4) {
return
}
if (this.status === 200) {
resolve(this.response)
} else {
reject(new Error(this.statusText))
}
}
const client = new XMLHttpRequest()
if (data.type === 'POST') {
client.open('POST', data.url)
client.onreadystatechange = handler
client.setRequestHeader('Content-Type', 'application/json')
const params = data.params
client.send(JSON.stringify(params))
} else {
client.open('GET', data.url)
client.onreadystatechange = handler
client.send()
}
})
return promise
}
使用方法 :GET
const url = `${baseUrl}/xxx/xxx?${paramsStr}`
getJSON({
url
}).then(res => {
const dataRes = JSON.parse(res)
})
使用方法 :POST
const url = `${baseUrl}/xxx/xxx`
getJSON({
url,
params: {
id:123,
name:222
},
type: 'POST'
}).then(res => {
const dataRes = JSON.parse(res)
})