Javascript XMLHttpRequest包含非空响应,但XMLHttpRequest.response为<;清空字符串>;
我用以下代码发送HTTP请求并接收响应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
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)