You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
GenFlightRec/WebContent/default/js/script.js

54 lines
1.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

const chatHistory = document.getElementById('chat-history');
const userInput = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');
sendBtn.addEventListener('click', sendMessage);
userInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendMessage();
}
});
function sendMessage() {
const message = userInput.value.trim();
if (message) {
addMessageToChat('user', message);
userInput.value = '';
callAIAPI(message);
}
}
function addMessageToChat(sender, message) {
const messageElement = document.createElement('div');
messageElement.classList.add('message', `${sender}-message`);
messageElement.innerHTML = message; // 使用innerHTML以支持HTML格式
chatHistory.appendChild(messageElement);
chatHistory.scrollTop = chatHistory.scrollHeight;
}
async function callAIAPI(prompt) {
try {
const response = await fetch('/air_ticket_book/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `prompt=${encodeURIComponent(prompt)}`
});
if (!response.ok) {
throw new Error('API请求失败');
}
const result = await response.json();
console.log('API响应:', result); // 添加这行来查看完整的响应
// 直接使用result.text因为服务器返回的JSON结构中text是在顶层
const aiResponse = result.text || '抱歉,我无法理解您的问题。';
addMessageToChat('ai', aiResponse);
} catch (error) {
console.error('Error:', error);
addMessageToChat('ai', '抱歉出现了一些问题。请稍后再试123。');
}
}