up_fail / chat_template.html
DmitrMakeev's picture
Create chat_template.html
b06f025 verified
raw
history blame
3.57 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Online Chat</title>
<style>
body {
font-family: Arial, sans-serif;
}
.chat-box {
height: 300px;
overflow-y: scroll;
border: 1px solid #ccc;
padding: 10px;
}
</style>
</head>
<body>
<h1>🧊 Добро пожаловать в онлайн чат!</h1>
<div class="chat-box" id="chat-box"></div>
<input type="text" id="nickname" placeholder="Ваше имя">
<button onclick="joinChat()">Войти в чат</button>
<input type="text" id="message" placeholder="Текст сообщения ...">
<button onclick="sendMessage()">Отправить</button>
<button onclick="leaveChat()">Выйти из чата</button>
<script>
let nickname = '';
let last_idx = 0;
async function joinChat() {
nickname = document.getElementById('nickname').value;
const response = await fetch('/chat_api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({action: 'join', nickname: nickname})
});
const data = await response.json();
if (data.status === 'success') {
document.getElementById('chat-box').innerHTML += `<p>${data.message}</p>`;
refreshChat();
} else {
alert(data.message);
}
}
async function sendMessage() {
const msg = document.getElementById('message').value;
const response = await fetch('/chat_api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({action: 'send', nickname: nickname, msg: msg})
});
const data = await response.json();
if (data.status === 'success') {
document.getElementById('message').value = '';
refreshChat();
}
}
async function leaveChat() {
const response = await fetch('/chat_api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({action: 'leave', nickname: nickname})
});
const data = await response.json();
if (data.status === 'success') {
document.getElementById('chat-box').innerHTML += `<p>${data.message}</p>`;
nickname = '';
refreshChat();
}
}
async function refreshChat() {
const response = await fetch('/chat_api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({action: 'refresh', last_idx: last_idx})
});
const data = await response.json();
if (data.status === 'success') {
data.messages.forEach(msg => {
document.getElementById('chat-box').innerHTML += `<p>${msg[0]}: ${msg[1]}</p>`;
});
last_idx = data.last_idx;
}
setTimeout(refreshChat, 1000);
}
</script>
</body>
</html>