Answer the question
In order to leave comments, you need to log in
Why does trying to read the response JS property of the XMLHttpRequest object return an empty string despite the data in it?
Hello, I ran into a problem creating pagination on scroll using Ajax. When trying to read the response or responseText property of the XMLHttpRequest object, an empty string is returned, although the resulting html code is displayed in the browser's debug console.
I will warn you in advance that JavaScript is not my main language and this is the first time I have encountered such a problem.
Debug console:
code:
function send_request(url, method = "GET", onsuccess = () => {
}, onerror = () => {
}, data = {}) {
var request = new XMLHttpRequest();
request.open(method, url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
if (method === "POST") {
request.setRequestHeader('X-CSRFToken', csrftoken);
}
request.setRequestHeader('x-requested-with', 'XMLHttpRequest');
var ready_to_react = true;
request.onreadystatechange = () => {
if (request.status === 200 && ready_to_react === true) {
ready_to_react = false;
onsuccess(request);
} else {
ready_to_react = false;
onerror(request);
}
}
if (data) {
request.send(JSON.stringify(data));
} else {
request.send();
}
ready_to_react = true;
console.log(ready_to_react);
}
var page = "{{ page_obj.number }}";
var empty_page = false;
var block_request = false;
window.onscroll = () => {
var document_height = Math.max(document.body.scrollHeight, document.body.offsetHeight);
var window_height = Math.max(screen.height, screen.availHeight, window.innerHeight,
window.outerHeight,)
var margin = document_height - window_height - 100;
if (window.scrollY > margin && empty_page === false && block_request === false) {
page++;
console.log(page)
block_request = true;
send_request("?page=" + page,
method = "GET",
onsuccess = (request) => {
block_request = false;
document.getElementById("image-list").innerHTML += request.response;
// При просмотре в браузере здесь есть аттрибут response и там есть html код
console.log(request)
// Здесь выводит пустоту
console.log(request.response);
},
onerror = (request) => {
empty_page = true;
})
}
}
Answer the question
In order to leave comments, you need to log in
onsuccess = (request) => {
block_request = false;
document.getElementById("image-list").innerHTML += request.response;
// При просмотре в браузере здесь есть аттрибут response и там есть html код
console.log(request)
// Здесь выводит пустоту
console.log(request.response);
},
request.onreadystatechange = () => {
if (request.status === 200 && ready_to_react === true) {
ready_to_react = false;
onsuccess(request);
} else {
ready_to_react = false;
onerror(request);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question