Javascript XMLHttpRequest包含非空响应,但XMLHttpRequest.response为<;清空字符串>;

Javascript XMLHttpRequest包含非空响应,但XMLHttpRequest.response为<;清空字符串>;,javascript,debugging,xmlhttprequest,Javascript,Debugging,Xmlhttprequest,我用以下代码发送HTTP请求并接收响应 var xhr=new-XMLHttpRequest() var等待=真 var sup=此 var userId=userInfo.userId var userType='student' if(userInfo.type==2){ 用户类型='professor' } xhr.onreadystatechange=函数(){ 试一试{ if(this.status==200&&waiting){ 等待=错误; var课程 试一试{ courses=J

我用以下代码发送HTTP请求并接收响应

var xhr=new-XMLHttpRequest()
var等待=真
var sup=此
var userId=userInfo.userId
var userType='student'
if(userInfo.type==2){
用户类型='professor'
}
xhr.onreadystatechange=函数(){
试一试{
if(this.status==200&&waiting){
等待=错误;
var课程
试一试{
courses=JSON.parse(xhr.response)
}捕获(杰尔){
课程=[]
}
sup.courseArray=课程;
控制台日志(辅助课程阵列)
辅助渲染()
}
}捕获(错误){}
}
xhr.open('GET','http://localhost:8080/course/read/'+userType+'Id/'+userId)
xhr.send()
如您所见,我只在回调中访问
response
,因此服务器已经响应,
xhr
已经在该点初始化。如果我只调用
console.log(xhr)
,我可以清楚地看到
响应
是一个非空字符串:

响应:“[{\'id\':1,\'professorId\':1,\'name\':\'java\',\'code\':\'CS1017\'””

但是,如果我调用
console.log(xhr.response)
,我会得到


有人知道我为什么会看到这种差异吗?

为什么不改用JS native fetch呢

var waiting = true
var sup = this
var userId = userInfo.userId
var userType = 'student'
if(userInfo.type == 2) {
   userType = 'professor'
}

fetch('http://localhost:8080/course/read/' + userType + 'Id/' + userId)
.then(r => r.json())
.then((response) => {
    waiting = false;
   sup.courseArray = response;
   console.log(sup.courseArray);
   sup.render();
})
.catch((e) => {
     waiting = false;
     console.log(e);
});

this.status==200
将在
xhr.readyState==2
时为真,但在
xhr.readyState==4
之前不会完全满足请求;在
readyState==2时
响应
仍为空

console.log(xhr)
最终将在
readyState==4
显示状态,但这比您的代码尝试访问
xhr.response
时晚了2个readyState

您必须检查
status==200
readyState==4
是否为
true
,以确保完整的
响应已到达。

尝试改用JSON.parse(this.response)