你代码错误有点多
1.两个new
2.this换成xhr,箭头函数this这个知识点查下吧
3.onsetRequestHeader没有这个函数,应该是setRequestHeader
4.设置格式为json不能获取responseText,必须设置responseType为text才行,另外改成response也行
贴上我改后的代码
let getJson = url =>{
let promise = new Promise((resolve,reject) =>{
let xhr = new XMLHttpRequest();
xhr.open("GET",url,true);
xhr.onreadystatechange = () =>{
if(xhr.readyState !== 4){
return;
}
if(xhr.status == 200){
resolve(xhr.response);
}else{
reject(new Error(xhr.statusText))
}
}
xhr.responseType = 'json';
xhr.setRequestHeader('Accept','application/json');
xhr.send(null);
});
return promise;
};
getJson("getDate.json").then((json) =>{console.log(json);},(err)=>{console.log(err)});