chatbot / static /js /main.js
tudeplom's picture
Update static/js/main.js
494d6fc verified
// Lấy các phần tử DOM
var messages = document.querySelector('.message-list');
var btn = document.querySelector('.btn');
var input = document.querySelector('input');
// Thêm sự kiện cho nút Send và phím Enter
btn.addEventListener('click', sendMessage);
input.addEventListener('keyup', function(e) {
if (e.key === 'Enter') sendMessage();
});
// Tải lịch sử chat khi trang load
function loadHistory() {
fetch('/history')
.then(response => response.json())
.then(data => {
for (let i = 0; i < data.length; i++) {
if (data[i].role === 'User') {
addMessage({ FROM: 'User', MESSAGE: data[i].content }, 'primary');
} else if (data[i].role === 'assistant') {
addMessage({ FROM: 'Oshi no Ko', MESSAGE: data[i].content }, 'secondary');
}
}
})
.catch(error => console.error('Error:', error));
}
loadHistory();
// Hàm gửi tin nhắn
function sendMessage() {
var msg = input.value.trim();
if (!msg) return; // Không gửi tin nhắn rỗng
// Hiển thị tin nhắn người dùng
addMessage({ FROM: 'User', MESSAGE: msg }, 'primary');
// Xóa input sau khi gửi
input.value = '';
// Gửi request đến server Flask
fetch('/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: msg })
})
.then(response => response.json())
.then(data => {
// Hiển thị phản hồi từ chatbot
addMessage({ FROM: 'Oshi no Ko', MESSAGE: data.MESSAGE }, 'secondary');
})
.catch(error => console.error('Error:', error));
}
// Hàm thêm tin nhắn vào giao diện
function addMessage(msg, typeMessage = 'primary') {
writeLine(`<span>${msg.FROM}</span><br><br> ${msg.MESSAGE}`, typeMessage);
}
// Hàm tạo dòng tin nhắn
function writeLine(text, typeMessage) {
var message = document.createElement('li');
message.classList.add('message-item', 'item-' + typeMessage);
message.innerHTML = text;
messages.appendChild(message);
messages.scrollTop = messages.scrollHeight; // Cuộn xuống cuối cùng
}