|
使用HTML、CSS和JavaScript来创建一个简单的聊天界面,然后通过JavaScript调用ChatGPT的API来获取回答使用HTML、CSS和JavaScript来创建一个简单的聊天界面,然后通过JavaScript调用ChatGPT的API来获取回答。 HTML代码: <html> <head> <meta charset="utf-8"> <title>ChatGPT</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="chat-window"> <div class="chat-header"> <h2>ChatGPT</h2> </div> <div class="chat-body" id="chat-body"> <div class="chat-message"> <div class="chat-message-content"> <p>Welcome! How can I help you?</p> </div> </div> </div> <div class="chat-input"> <input type="text" id="chat-input" placeholder="Type your message here..."> <button id="send-button">Send</button> </div> </div> <script src="script.js"></script> </body></html> 这里我们使用了一个简单的HTML结构来创建一个聊天窗口,其中包含一个头部、一个消息区域和一个输入框。CSS样式表可以自行定义,这里不再赘述。 JavaScript代码: const chatBody = document.getElementById('chat-body');const chatInput = document.getElementById('chat-input');const sendButton = document.getElementById('send-button');// Define function to add a message to the chat windowfunction addMessage(message, isResponse) { const messageClass = isResponse ? 'chat-message-response' : 'chat-message'; const messageContent = `<div class="chat-message-content"><p>${message}</p></div>`; const messageElement = `<div class="${messageClass}">${messageContent}</div>`; chatBody.insertAdjacentHTML('beforeend', messageElement); chatBody.scrollTop = chatBody.scrollHeight; }// Define function to send a message to ChatGPTasync function sendMessage() { const query = chatInput.value; addMessage(query, false); chatInput.value = ''; const response = await fetch('/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: query }) }); const responseData = await response.json(); const answer = responseData.response; addMessage(answer, true); }// Attach click event listener to the send buttonsendButton.addEventListener('click', sendMessage);// Attach keypress event listener to the input boxchatInput.addEventListener('keypress', (event) => { if (event.key === 'Enter') { sendMessage(); } }); |