/
erioxis
/
web-nodejs
Обзор
Документация
Войти
/
erioxis
/
web-nodejs
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
public/lab7/task2/script.js
179 строк
8 KB
erioxis
lab11fix
15 дек 2025, 23:21
15 дек 2025, 23:21
70dc7ba
Код
Авторство
О чём код?
const STORAGE_KEY = 'registeredPeople'; function isLocalStorageAvailable() { try { const test = '__storage_test__'; localStorage.setItem(test, test); localStorage.removeItem(test); return true; } catch (e) { console.error("localStorage недоступен:", e); return false; } } if (!isLocalStorageAvailable()) { alert("Ваш браузер не поддерживает localStorage или он отключен. Некоторые функции могут не работать."); } document.getElementById('projectParticipation').addEventListener('change', function() { const projectNameField = document.getElementById('projectName'); projectNameField.style.display = this.checked ? 'block' : 'none'; if (!this.checked) { projectNameField.value = ''; } }); function savePerson() { if (!isLocalStorageAvailable()) { alert("Невозможно сохранить: localStorage недоступен."); return; } const form = document.getElementById('registrationForm'); const formData = new FormData(form); const person = { lastname: formData.get('lastname'), firstname: formData.get('firstname'), surname: formData.get('surname'), gender: formData.get('gender'), faculty: formData.get('faculty'), projectParticipation: formData.get('projectParticipation') === 'true', projectName: formData.get('projectName') || '' }; let people = JSON.parse(localStorage.getItem(STORAGE_KEY)) || []; people.push(person); localStorage.setItem(STORAGE_KEY, JSON.stringify(people)); loadPeopleTable(); form.reset(); document.getElementById('projectName').style.display = 'none'; console.log("Человек сохранён в localStorage:", person); } function loadPeopleTable() { if (!isLocalStorageAvailable()) { document.getElementById('peopleTableBody').innerHTML = '<tr><td colspan="9">localStorage недоступен.</td></tr>'; return; } const tableBody = document.getElementById('peopleTableBody'); tableBody.innerHTML = ''; const people = JSON.parse(localStorage.getItem(STORAGE_KEY)) || []; people.forEach((person, index) => { const row = document.createElement('tr'); row.setAttribute('data-index', index); const participationText = person.projectParticipation ? 'Да' : 'Нет'; row.innerHTML = ` <td><button type="button" class="select-btn" onclick="selectPerson(${index})">✓</button></td> <td>${person.lastname}</td> <td>${person.firstname}</td> <td>${person.surname}</td> <td>${person.gender}</td> <td>${person.faculty}</td> <td>${participationText}</td> <td>${person.projectName}</td> <td><button type="button" class="delete-btn" onclick="deletePerson(${index})">×</button></td> `; tableBody.appendChild(row); }); } let selectedPersonIndex = null; function selectPerson(index) { if (selectedPersonIndex !== null) { const prevRow = document.querySelector(`tr[data-index="${selectedPersonIndex}"]`); if (prevRow) prevRow.classList.remove('selected'); } const row = document.querySelector(`tr[data-index="${index}"]`); if (row) { row.classList.add('selected'); } selectedPersonIndex = index; console.log("Выбран человек с индексом:", index); } function deletePerson(index) { if (!isLocalStorageAvailable()) { alert("Невозможно удалить: localStorage недоступен."); return; } let people = JSON.parse(localStorage.getItem(STORAGE_KEY)) || []; if (index >= 0 && index < people.length) { people.splice(index, 1); localStorage.setItem(STORAGE_KEY, JSON.stringify(people)); if (selectedPersonIndex === index) { selectedPersonIndex = null; } loadPeopleTable(); console.log("Человек с индексом", index, "удалён из localStorage."); } } function makeInitials() { if (selectedPersonIndex === null) { alert('Пожалуйста, выберите человека из таблицы.'); return; } if (!isLocalStorageAvailable()) { alert("Невозможно получить данные: localStorage недоступен."); return; } const people = JSON.parse(localStorage.getItem(STORAGE_KEY)) || []; const person = people[selectedPersonIndex]; if (!person) { console.error("Человек с индексом", selectedPersonIndex, "не найден в localStorage."); return; } const fullname = `${person.lastname} ${person.firstname} ${person.surname}`; const url = `/api/lab7/task2/makeInitials?fullname=${encodeURIComponent(fullname)}`; fetch(url) .then(response => { if (!response.ok) { return response.json().then(err => { throw new Error(err.error || 'Network response was not ok'); }); } return response.json(); }) .then(data => { const resultDiv = document.getElementById('initialsResult'); const formattedInitials = `${data.lastname} ${data.firstnameLetter}${data.surnameLetter}`; resultDiv.innerText = `Инициалы: ${formattedInitials}`; resultDiv.style.display = 'block'; document.getElementById('statusResult').style.display = 'none'; }) .catch(error => { console.error('Error fetching initials:', error); document.getElementById('initialsResult').innerText = `Ошибка: ${error.message}`; document.getElementById('initialsResult').style.display = 'block'; }); } function makeProjectStatus() { if (selectedPersonIndex === null) { alert('Пожалуйста, выберите человека из таблицы.'); return; } if (!isLocalStorageAvailable()) { alert("Невозможно получить данные: localStorage недоступен."); return; } const people = JSON.parse(localStorage.getItem(STORAGE_KEY)) || []; const person = people[selectedPersonIndex]; if (!person) { console.error("Человек с индексом", selectedPersonIndex, "не найден в localStorage."); return; } const fullname = `${person.lastname} ${person.firstname} ${person.surname}`; const participationStr = person.projectParticipation ? 'true' : 'false'; const url = `/api/lab7/task2/makeProjectStatus?fullname=${encodeURIComponent(fullname)}&projectParticipation=${participationStr}`; fetch(url) .then(response => { if (!response.ok) { return response.json().then(err => { throw new Error(err.error || 'Network response was not ok'); }); } return response.json(); }) .then(data => { const resultDiv = document.getElementById('statusResult'); const formattedStatus = `${data.lastname} ${data.firstnameLetter}${data.surnameLetter} ${data.projectParticipant}`; resultDiv.innerText = `Статус проекта: ${formattedStatus}`; resultDiv.style.display = 'block'; document.getElementById('initialsResult').style.display = 'none'; }) .catch(error => { console.error('Error fetching project status:', error); document.getElementById('statusResult').innerText = `Ошибка: ${error.message}`; document.getElementById('statusResult').style.display = 'block'; }); } document.addEventListener('DOMContentLoaded', function() { loadPeopleTable(); });