什么是ajax?
let xhr = new XMLHttpRequest()
xhr.open('POST', '/xxxx')
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText)
}
}
xhr.send('a=1&b=2')
封装一个ajax:
function ajax(opts){
let url = opts.url
let type = opts.type || 'GET'
let dataType = opts.dataType || 'json'
let onsuccess = opts.onsuccess || function(){}
let onerror = opts.onerror || function(){}
let data = opts.data || {}
let dataStr = []
for(let key in data){
dataStr.push(key + '=' + data[key])
}
dataStr = dataStr.join('&')
//判断请求类型
if(type === 'GET'){
url += '?' + dataStr
}
let xhr = new XMLHttpRequest()
xhr.open(type, url, true)
xhr.onload = function(){
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: '[http://api.xxx.com/weather.php](http://api.xxx.com/weather.php)',
data: {
city: '杭州'
},
onsuccess: function(res){
console.log(res)
},
onerror: function(){
console.log('服务器异常')
}
})