首先定义一个json数据
{
"status": "200",
"msg": "成功",
"data": {
"userList": [{
"id":"1",
"name": "张三"
},
{
"id":"2",
"name": "李四"
}]
}
}
然后用promise封装ajax实现axios的get方法
var axios = {
get: function(url) {
return new Promise((resolve,reject) => {
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return
}
if (xhr.status = 1) {
resolve(xhr.responseText)
}else{
console.log('请求失败!')
}
}
xhr.open('GET', url, true)
xhr.send()
})
}
}
let text1 = axios.get('test-data.json')//传入url
text1.then(res=>{
let text2 = JSON.parse(res)//把获得的json字符串转换成对象
console.log(text2.data.userList[0].name) //张三
})