index.html 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width" />
  6. <title>Список пользователей</title>
  7. <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.0/css/bootstrap.min.css" rel="stylesheet" />
  8. </head>
  9. <body>
  10. <h2>Список пользователей</h2>
  11. <form name="userForm">
  12. <input type="hidden" name="id" value="0" />
  13. <div class="form-group col-md-5">
  14. <label for="name">Имя:</label>
  15. <input class="form-control" name="name" />
  16. </div>
  17. <div class="form-group col-md-5">
  18. <label for="age">Возраст:</label>
  19. <input class="form-control" name="age" type="number" />
  20. </div>
  21. <div class="panel-body">
  22. <button type="submit" id="submit" class="btn btn-primary">Сохранить</button>
  23. <a id="reset" class="btn btn-primary">Сбросить</a>
  24. </div>
  25. </form>
  26. <table class="table table-condensed table-striped col-md-6">
  27. <thead><tr><th>Id</th><th>Имя</th><th>возраст</th><th></th></tr></thead>
  28. <tbody>
  29. </tbody>
  30. </table>
  31. <div>2019 © Metanit.com</div>
  32. <script>
  33. // Получение всех пользователей
  34. async function GetUsers() {
  35. // отправляет запрос и получаем ответ
  36. const response = await fetch("/api/users", {
  37. method: "GET",
  38. headers: { "Accept": "application/json" }
  39. });
  40. // если запрос прошел нормально
  41. if (response.ok === true) {
  42. // получаем данные
  43. const users = await response.json();
  44. let rows = document.querySelector("tbody");
  45. users.forEach(user => {
  46. // добавляем полученные элементы в таблицу
  47. rows.append(row(user));
  48. });
  49. }
  50. }
  51. // Получение одного пользователя
  52. async function GetUser(id) {
  53. const response = await fetch("/api/users/" + id, {
  54. method: "GET",
  55. headers: { "Accept": "application/json" }
  56. });
  57. if (response.ok === true) {
  58. const user = await response.json();
  59. const form = document.forms["userForm"];
  60. form.elements["id"].value = user.id;
  61. form.elements["name"].value = user.name;
  62. form.elements["age"].value = user.age;
  63. }
  64. }
  65. // Добавление пользователя
  66. async function CreateUser(userName, userAge) {
  67. const response = await fetch("api/users", {
  68. method: "POST",
  69. headers: { "Accept": "application/json", "Content-Type": "application/json" },
  70. body: JSON.stringify({
  71. name: userName,
  72. age: parseInt(userAge, 10)
  73. })
  74. });
  75. if (response.ok === true) {
  76. const user = await response.json();
  77. reset();
  78. document.querySelector("tbody").append(row(user));
  79. }
  80. }
  81. // Изменение пользователя
  82. async function EditUser(userId, userName, userAge) {
  83. const response = await fetch("api/users", {
  84. method: "PUT",
  85. headers: { "Accept": "application/json", "Content-Type": "application/json" },
  86. body: JSON.stringify({
  87. id: parseInt(userId, 10),
  88. name: userName,
  89. age: parseInt(userAge, 10)
  90. })
  91. });
  92. if (response.ok === true) {
  93. const user = await response.json();
  94. reset();
  95. document.querySelector("tr[data-rowid='" + user.id + "']").replaceWith(row(user));
  96. }
  97. }
  98. // Удаление пользователя
  99. async function DeleteUser(id) {
  100. const response = await fetch("/api/users/" + id, {
  101. method: "DELETE",
  102. headers: { "Accept": "application/json" }
  103. });
  104. if (response.ok === true) {
  105. const user = await response.json();
  106. document.querySelector("tr[data-rowid='" + user.id + "']").remove();
  107. }
  108. }
  109. // сброс формы
  110. function reset() {
  111. const form = document.forms["userForm"];
  112. form.reset();
  113. form.elements["id"].value = 0;
  114. }
  115. // создание строки для таблицы
  116. function row(user) {
  117. const tr = document.createElement("tr");
  118. tr.setAttribute("data-rowid", user.id);
  119. const idTd = document.createElement("td");
  120. idTd.append(user.id);
  121. tr.append(idTd);
  122. const nameTd = document.createElement("td");
  123. nameTd.append(user.name);
  124. tr.append(nameTd);
  125. const ageTd = document.createElement("td");
  126. ageTd.append(user.age);
  127. tr.append(ageTd);
  128. const linksTd = document.createElement("td");
  129. const editLink = document.createElement("a");
  130. editLink.setAttribute("data-id", user.id);
  131. editLink.setAttribute("style", "cursor:pointer;padding:15px;");
  132. editLink.append("Изменить");
  133. editLink.addEventListener("click", e => {
  134. e.preventDefault();
  135. GetUser(user.id);
  136. });
  137. linksTd.append(editLink);
  138. const removeLink = document.createElement("a");
  139. removeLink.setAttribute("data-id", user.id);
  140. removeLink.setAttribute("style", "cursor:pointer;padding:15px;");
  141. removeLink.append("Удалить");
  142. removeLink.addEventListener("click", e => {
  143. e.preventDefault();
  144. DeleteUser(user.id);
  145. });
  146. linksTd.append(removeLink);
  147. tr.appendChild(linksTd);
  148. return tr;
  149. }
  150. // сброс значений формы
  151. document.getElementById("reset").click(function (e) {
  152. e.preventDefault();
  153. reset();
  154. })
  155. // отправка формы
  156. document.forms["userForm"].addEventListener("submit", e => {
  157. e.preventDefault();
  158. const form = document.forms["userForm"];
  159. const id = form.elements["id"].value;
  160. const name = form.elements["name"].value;
  161. const age = form.elements["age"].value;
  162. if (id == 0)
  163. CreateUser(name, age);
  164. else
  165. EditUser(id, name, age);
  166. });
  167. // загрузка пользователей
  168. GetUsers();
  169. </script>
  170. </body>
  171. </html>