48 lines
1.5 KiB
JavaScript
48 lines
1.5 KiB
JavaScript
document.addEventListener('DOMContentLoaded', async () => {
|
||
const app = document.getElementById('app');
|
||
const resp = await fetch('/api/generate');
|
||
const data = await resp.json();
|
||
if (data.error) {
|
||
app.innerHTML = `<p>Ошибка получения теста: ${data.error}</p>`;
|
||
return;
|
||
}
|
||
if (!Array.isArray(data) || data.length === 0) {
|
||
app.innerHTML = `<p>Нет данных</p>`;
|
||
return;
|
||
}
|
||
const questions = data;
|
||
let current = 0;
|
||
const answers = new Array(questions.length).fill(null);
|
||
|
||
function renderQuestion(i) {
|
||
const q = questions[i];
|
||
const opts = q.options || [];
|
||
const html = `<div class='question'>
|
||
<p><strong>Вопрос ${i+1}:</strong> ${q.question}</p>
|
||
<div class='options'>${opts.map((opt, idx) => `<button data-idx='${idx}'>${opt}</button>`).join('')}</div>
|
||
</div>`;
|
||
app.innerHTML = html;
|
||
document.querySelectorAll('.options button').forEach(btn => {
|
||
btn.onclick = () => {
|
||
answers[i] = parseInt(btn.dataset.idx,10);
|
||
if (i+1 < questions.length) renderQuestion(i+1);
|
||
else showResult();
|
||
};
|
||
});
|
||
}
|
||
|
||
function showResult() {
|
||
let correct = 0;
|
||
questions.forEach((q, idx) => {
|
||
if (answers[idx] === q.correct) correct++;
|
||
});
|
||
const percent = Math.round((correct / questions.length) * 100);
|
||
const verdict = percent >= 80 ? 'Прошел' : 'Не прошел';
|
||
app.innerHTML = `<div class='result'>
|
||
<p>Результат: ${percent}% – ${verdict}</p>
|
||
</div>`;
|
||
}
|
||
|
||
renderQuestion(current);
|
||
});
|