const ajax = (options) => {
let url = options.url
let type = options.type || 'GET'
let dataType = options.dataType || 'json'
const onsuccess = options.onsuccess || function(){}
const onerror = options.onerror || function(){}
const data = options.data || {}
const dataStr = []
for(let key in data){
dataStr.push(key + '=' + data[key])
}
dataStr = dataStr.join('&')
if(type === 'GET'){
url += '?' + dataStr
}
const xhr = new XMLHttpRequest()
xhr.open(type,url,true)
xhr.onload = () => {
if((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304){
if(dataType === 'json'){
onsuccess( JSON.parse(xhr.responseText))
}else{
onsuccess( xhr.responseText)
}
}else{
onerror()
}
}
xhr.onerror = onerror
if(type === 'POST'){
xhr.send(dataStr)
}else{
xhr.send()
}
}
// 使用
ajax({
url: 'https://cn.bing.com/',
data: {
city: '武汉'
},
onsuccess: function(result){
console.log(result)
},
onerror: function(){
console.log('服务器异常')
}
})
网友评论