背景:一个几乎全静态页面的项目中,有一个地方涉及到了请求后端,不想从api/model从头写起,于是使用原生的xhr方法发get请求。
created() {
let requestApp = new XMLHttpRequest();//new一个请求
let that = this;
requestApp.onreadystatechange = function () {
if (requestApp.status === 200) {
//后台有做好拦截,所以前端比较简单,不需要设置拦截器,只是简单判断了是否成功返回
let json;
try {
json =JSON.parse(requestApp.responseText)
}catch (e){
console.warn("error!",e);
return;
}
that.downloadUrl = json.data.downloadUrl;
}
}
requestApp.open('GET', this.url);
requestApp.setRequestHeader("content-type", "application/json; charset=utf-8");
requestApp.send(null);
},
请求得到的内容是字符串,无法直接使用,需要用JSON.parse()方法转化为json对象。