V
V
Vladislav1052021-06-18 22:59:24
AJAX
Vladislav105, 2021-06-18 22:59:24

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


On the second call, an error occurs, saying that the response contains null.
Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null

What do I need to do to ensure that the function succeeds every time it is called?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2021-06-21
@Vladislav105

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 question

Ask a Question

731 491 924 answers to any question