Answer the question
In order to leave comments, you need to log in
How to reuse function with xmlhttprequest object?
Newbie, do not throw slippers)
I wrote the following function to receive news from the site:
function getNews(fileName, className, key, limit, offset = 0) {
xhr = new XMLHttpRequest();
xhr.error = popup('Ошибка при запросе к серверу', 'error.svg');
xhr.open('POST', 'server/' + fileName);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200)
document.querySelector(className).insertAdjacentHTML("beforeend", xhr.responseText);
}
xhr.send("key=" + key + "&limit=" + limit + "&offset=" + offset + ";");
console.log(xhr);
}
Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null
Answer the question
In order to leave comments, you need to log in
Try like this:
async function getNews(fileName, className, key, limit, offset) {
var params = new URLSearchParams();
params.append('key', key);
params.append('limit', limit);
params.append('offset', offset);
var body = params.toString();
var news = await (await fetch('server/' + fileName, {
'method': 'POST',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
'body': body
})).text();
if (document.querySelector(className)) {
document.querySelector(className).insertAdjacentHTML('beforeEnd', news);
} else {
console.log('Элемент соответствующий селектору '+className+' отсутствует на странице!');
}
console.log("Ответ сервера:\n" + news);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question