XMLHttpRequest содержит непустой ответ, но XMLHttpRequest.response

#javascript #debugging #xmlhttprequest

#javascript #отладка #xmlhttprequest

Вопрос:

Я отправляю HTTP-запросы и получаю ответы со следующим кодом:

 var xhr = new XMLHttpRequest()
var waiting = true
var sup = this
var userId = userInfo.userId
var userType = 'student'
if (userInfo.type == 2) {
    userType = 'professor'
}
xhr.onreadystatechange = function() {
    try {
        if (this.status == 200 amp;amp; waiting) {
            waiting = false;
            var courses
            try {
                courses = JSON.parse(xhr.response)
            } catch (jerr) {
                courses = []
            }
            sup.courseArray = courses;
            console.log(sup.courseArray)
            sup.render()
        }
    } catch (err) {}
}
xhr.open('GET', 'http://localhost:8080/course/read/'   userType   'Id/'   userId)
xhr.send()
 

Как вы можете видеть, я обращаюсь только response к обратному вызову, поэтому сервер ответил и xhr был инициализирован в этот момент. Если я просто вызываю console.log(xhr) , я могу ясно видеть response , что это непустая строка:

response: "[{"id":1,"professorId":1,"name":"java","code":"CS1017"}]"

Однако, если я вызываю console.log(xhr.response) , я получаю

<empty string>

Кто-нибудь знает, почему я вижу это несоответствие?

Комментарии:

1. Попробуйте вместо этого использовать JSON.parse(this.response)

Ответ №1:

this.status == 200 будет иметь значение true, как только xhr.readyState == 2 , но запрос не будет полностью выполнен до тех пор, пока xhr.readyState == 4 ; at readyState == 2 response все равно будет пустым.

console.log(xhr) в конечном итоге будет отображаться статус at readyState == 4 , но это на 2 состояния готовности позже, чем когда ваш код пытается получить доступ xhr.response .

Вы должны проверить, что оба status == 200 и readyState == 4 true должны быть уверены response , что прибыло полное сообщение.

Ответ №2:

почему бы не попробовать использовать вместо этого собственную выборку JS

 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);
});