Answer the question
In order to leave comments, you need to log in
How to update block using ajax?
Hello. How to update one block without reloading the whole page? I know there are many such questions on the Internet, but the code that I copied from the Internet did not work for me. Let's say I have:
<div id = "block">
...
</div>
Answer the question
In order to leave comments, you need to log in
An example of a function for selectively updating content:
async function elementUpdate(selector) {
try {
var html = await (await fetch(location.href)).text();
var newdoc = new DOMParser().parseFromString(html, 'text/html');
document.querySelector(selector).outerHTML = newdoc.querySelector(selector).outerHTML;
console.log('Элемент '+selector+' был успешно обновлен');
return true;
} catch(err) {
console.log('При обновлении элемента '+selector+' произошла ошибка:');
console.dir(err);
return false;
}
}
elementUpdate('div#block');
// Запуск асинхронного кода:
(async function() {
// Бесконечный цикл:
while (true) {
await elementUpdate('div#block'); // Обновляем блок
// Выжидаем 1000 миллисекунд, а потом код внутри while выполняется вновь:
await new Promise(function(success) { setTimeout(success, 1000); });
}
})();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question