最近在学ES6的语法,复习了下ajax和promise。
选取了几个有代表性的例子,反复写了几遍,加深了不少理解。
ajax
const xhr = new XMLHttpRequest()
xhr.open('GET', '/hello.json', true)
xhr.onreadystatechange = ()=>{
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText)
}
}
xhr.send()
ajax封装
function ajax(opts){
var url = opts.url
var type = opts.type || 'GET'
var dataType = opts.dataType || 'json'
var onsuccess = opts.onsuccess || function(){}
var onerror = opts.onerror || function(){}
var data = opts.data || {}
var dataStr = []
for(var key in data){
dataStr.push(key + '=' + data[key])
}
dataStr = dataStr.join('&')
if(type === 'GET'){
url += '?' + dataStr
}
var 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.jirengu.com/weather.php',
data: {
city: '北京'
},
onsuccess: function(ret){
console.log(ret)
},
onerror: function(){
console.log('服务器异常')
}
})
promise
function 掷骰子(){
return new Promise((resolve,reject)=>{
let n = parseInt(Math.random()*6+1,10)
return resolve(n)
})
}
掷骰子().then((x)=>{
console.log('骰子的点数是'+x)
})
上面封装的ajax我们也能够结合promise
function ajax(opts){
const promise = new Promise((resolve,reject)=>{
var url = opts.url
var type = opts.type || 'GET'
var dataType = opts.dataType || 'json'
var onsuccess = opts.onsuccess || function(){}
var onerror = opts.onerror || function(){}
var data = opts.data || {}
var dataStr = []
for(var key in data){
dataStr.push(key + '=' + data[key])
}
dataStr = dataStr.join('&')
if(type === 'GET'){
url += '?' + dataStr
}
var xhr = new XMLHttpRequest()
xhr.open(type, url, true)
xhr.onload = function(){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
//成功了
if(dataType === 'json'){
resolve(JSON.parse(xhr.responseText))
}else{
resolve(xhr.responseText)
}
}
}
xhr.onerror = function(){
reject('获取数据失败')
}
if(type === 'POST'){
xhr.send(dataStr)
}else{
xhr.send()
}
})
return promise
}
ajax({
url: 'http://api.jirengu.com/weather.php',
data: {
city: '北京'
}
}).then(function(ret){
console.log(ret)
}).catch(function(){
console.log('服务器异常')
})
网友评论