以上代码结合view使用
时间: 2023-11-27 15:51:13 浏览: 27
好的,以下是结合view使用的代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ChitGPT Chatbot</title>
<link rel="stylesheet" href="https://unpkg.com/mvp.css">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<header class="mvp-header">
<h1 class="mvp-title">ChitGPT Chatbot</h1>
</header>
<main class="mvp-main">
<div class="chat-container">
<div class="chat-log" id="chat-log"></div>
<div class="chat-input">
<input type="text" id="user-input" placeholder="Type your message here...">
<button id="send-btn">Send</button>
</div>
</div>
</main>
<script>
const chatLog = document.getElementById('chat-log');
const userInput = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');
// Sends user input to the server and displays the response
function sendMessage() {
const userMessage = userInput.value;
if (userMessage.trim() === '') {
return;
}
chatLog.innerHTML += `<div class="chat-bubble user-bubble">${userMessage}</div>`;
axios.post('/chat', { user_message: userMessage })
.then(response => {
const botMessage = response.data.bot_message;
chatLog.innerHTML += `<div class="chat-bubble bot-bubble">${botMessage}</div>`;
})
.catch(error => {
console.error(error);
});
userInput.value = '';
}
sendBtn.addEventListener('click', sendMessage);
userInput.addEventListener('keydown', event => {
if (event.key === 'Enter') {
sendMessage();
}
});
</script>
</body>
</html>
```
在这个示例中,我们使用了 MVP.css 来美化界面,并使用了 axios 库来发送 POST 请求和接收响应。我们向 `/chat` 路径发送一个包含用户输入的 JSON 对象,并从响应中获取机器人的回复。我们将用户输入和机器人回复分别显示为两个不同的气泡。用户可以点击发送按钮或按下回车键来发送消息。