Answer the question
In order to leave comments, you need to log in
How to make sequential ajax output on button click?
I want to display data from 2 different files sequentially (first from the 1st, then from the 2nd) by pressing a button.
In this case, it turns out that the 2nd is displayed faster, and the 1st is not displayed at all.
let result = document.getElementById('result');
let button = document.getElementById('button');
button.addEventListener('click', function() {
let promise = fetch('ajax/first-p');
let promise2 = fetch('ajax/second-p');
promise.then(
function(response){
return response.text();
}).then(
function(text){
result.innerHTML = text;
}
)
promise2.then(
function(response){
return response.text();
}).then(
function(text){
result.innerHTML = text;
}
)
});
Answer the question
In order to leave comments, you need to log in
Use async functions :
let result = document.querySelector('#result');
let button = document.querySelector('#button');
button.addEventListener('click', async function() {
result.innerHTML = await (await fetch('ajax/first-p')).text();
result.innerHTML = await (await fetch('ajax/second-p')).text();
});
let result = document.querySelector('#result');
let button = document.querySelector('#button');
button.addEventListener('click', async function() {
result.innerHTML = await (await fetch('ajax/first-p')).text();
await wait(2000); // Ждём 2 секунды, только потом продолжаем
result.innerHTML = await (await fetch('ajax/second-p')).text();
});
// Функция для выставления задержек:
function wait(ms) {
return new Promise(function(success) {
setTimeout(function() {
success(true);
}, ms);
});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question