const chatbox = document.getElementById(‘chatbox’);
const userInput = document.getElementById(‘user-input’);
function sendUserInput() {
const userMessage = userInput.value;
if (userMessage !== ”) {
addMessage(‘user’, userMessage);
userInput.value = ”;
sendToBot(userMessage);
}
}
function sendToBot(message) {
// 修改成自己的后台服务器接口,比如 ajax 发送数据到后台,回传后响应 sendToBotResponse 函数
const url = ‘https://www.example.com/bot/response’;
fetch(url, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
input_message: message
})
})
.then(response => response.json())
.then(data => sendToBotResponse(data.bot_message))
.catch((error) => {
console.error(‘Error:’, error);
});
}
function sendToBotResponse(botMessage) {
addMessage(‘bot’, botMessage);
}
function addMessage(sender, message) {
const textClass = sender === ‘bot’ ? ‘bot-message’ : ‘user-message’;
const messageClass = sender === ‘bot’ ? ‘bot-text’ : ‘user-text’;
const text = ‘
‘;
chatbox.innerHTML += text;
chatbox.scrollTop = chatbox.scrollHeight;
}