-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtsn_todoapp_client.html
More file actions
170 lines (158 loc) · 6.33 KB
/
tsn_todoapp_client.html
File metadata and controls
170 lines (158 loc) · 6.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TSN Todo App</title>
<style>
/* Простые стили для удобного отображения */
body {
font-family: Arial, sans-serif;
margin: 20px;
max-width: 600px;
margin-left: auto;
margin-right: auto;
}
h1 {
text-align: center;
}
ul {
list-style: none;
padding: 0;
}
li {
padding: 10px;
border: 1px solid #ccc;
margin-bottom: 10px;
display: flex;
justify-content: space-between;
align-items: center;
}
input, button {
padding: 5px;
margin: 5px;
}
.completed {
text-decoration: line-through;
color: gray;
}
.error {
color: red;
text-align: center;
}
</style>
</head>
<body>
<h1>Список задач</h1>
<!-- Форма для создания/обновления задачи -->
<div>
<input type="text" id="taskDescription" placeholder="Введите задачу">
<button onclick="createTask()">Добавить</button>
</div>
<!-- Список задач -->
<ul id="taskList"></ul>
<!-- Сообщение об ошибке -->
<p id="errorMessage" class="error"></p>
<script>
// Базовый URL API
const API_URL = 'http://localhost:8080/api/tasks';
// Функция для очистки сообщения об ошибке
function clearError() {
document.getElementById('errorMessage').textContent = '';
}
// Функция для отображения ошибки
function showError(message) {
document.getElementById('errorMessage').textContent = message;
}
// Функция для получения и отображения всех задач
function fetchTasks() {
fetch(API_URL)
.then(response => {
if (!response.ok) throw new Error('Ошибка при загрузке задач');
return response.json();
})
.then(tasks => {
const taskList = document.getElementById('taskList');
taskList.innerHTML = ''; // Очищаем список
tasks.forEach(task => {
const li = document.createElement('li');
li.innerHTML = `
<span class="${task.completed ? 'completed' : ''}">
${task.description}
</span>
<div>
<button onclick="toggleTask(${task.id}, ${!task.completed})">
${task.completed ? 'Отменить' : 'Выполнить'}
</button>
<button onclick="deleteTask(${task.id})">Удалить</button>
</div>
`;
taskList.appendChild(li);
});
})
.catch(error => showError(error.message));
}
// Функция для создания новой задачи
function createTask() {
const description = document.getElementById('taskDescription').value;
if (!description) {
showError('Введите описание задачи');
return;
}
clearError();
fetch(API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description, completed: false })
})
.then(response => {
if (!response.ok) throw new Error('Ошибка при создании задачи');
return response.json();
})
.then(() => {
document.getElementById('taskDescription').value = ''; // Очищаем поле
fetchTasks(); // Обновляем список
})
.catch(error => showError(error.message));
}
// Функция для изменения статуса задачи (выполнена/не выполнена)
function toggleTask(id, completed) {
clearError();
fetch(`${API_URL}/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description: getTaskDescription(id), completed })
})
.then(response => {
if (!response.ok) throw new Error('Ошибка при обновлении задачи');
fetchTasks(); // Обновляем список
})
.catch(error => showError(error.message));
}
// Функция для получения описания задачи (для PUT-запроса)
function getTaskDescription(id) {
const tasks = document.querySelectorAll('#taskList li span');
for (let task of tasks) {
if (task.parentElement.querySelector('button').onclick.toString().includes(id)) {
return task.textContent.trim();
}
}
return '';
}
// Функция для удаления задачи
function deleteTask(id) {
clearError();
fetch(`${API_URL}/${id}`, {
method: 'DELETE'
})
.then(response => {
if (!response.ok) throw new Error('Ошибка при удалении задачи');
fetchTasks(); // Обновляем список
})
.catch(error => showError(error.message));
}
// Загружаем задачи при загрузке страницы
window.onload = fetchTasks;
</script>
</body>
</html>