123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Document</title>
- <link
- href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
- rel="stylesheet"
- />
- </head>
- <body class="container bg-info">
- <h2>Чатик</h2>
- <form name="chatForm">
- <div class="form-group">
- <input class="form-control" placeholder="Nick:" name="nick" />
- </div>
- <div class="form-group">
- <input class="form-control" placeholder="Message:" name="message" />
- </div>
- <div class="panel-body">
- <button type="submit" class="btn btn-sm btn-primary">Отправить</button>
- </div>
- </form>
- <table class="table table-condensed table-striped table-bordered">
- <thead>
- <tr>
- <th>Date</th>
- <th>Nick</th>
- <th>Message</th>
- </tr>
- </thead>
- <tbody></tbody>
- </table>
- <script>
- async function GetUsers() {
- const response = await fetch("/chat", {
- method: "GET",
- headers: { Accept: "application/json" },
- });
- if (response.ok === true) {
- const messagesData = await response.json();
- let rows = document.querySelector("tbody");
- messagesData.forEach((message) => {
- rows.append(row(message));
- });
- }
- }
- async function CreateMessage(nickName, messageText) {
- const response = await fetch("/chat", {
- method: "POST",
- headers: {
- Accept: "application/json",
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- nick: nickName,
- message: messageText,
- }),
- });
- if (response.ok === true) {
- const message = await response.json();
- reset();
- document.querySelector("tbody").append(row(message));
- }
- }
- function reset() {
- const form = document.forms["chatForm"];
- form.reset();
- }
- function row(messageItem) {
- const tr = document.createElement("tr");
- tr.setAttribute("data-rowid", messageItem.id);
- const idTd = document.createElement("td");
- idTd.append(messageItem.id);
- tr.append(idTd);
- const nameTd = document.createElement("td");
- nameTd.append(messageItem.nick);
- tr.append(nameTd);
- const messTd = document.createElement("td");
- messTd.append(messageItem.message);
- tr.append(messTd);
- return tr;
- }
- document.forms["chatForm"].addEventListener("submit", (e) => {
- e.preventDefault();
- const form = document.forms["chatForm"];
- const nick = form.elements["nick"].value;
- const message = form.elements["message"].value;
- CreateMessage(nick, message);
- });
- GetUsers();
- </script>
- </body>
- </html>
|