海门区文章资讯

利用Ajax实现智能回答的机器人示例代码

2026-04-02 13:01:01 浏览次数:0
详细信息

基于Ajax的智能对话机器人实现

我将创建一个使用Ajax与后端API交互的智能对话机器人界面。这个示例将模拟与AI助手的对话体验。

思路设计

创建简洁美观的聊天界面 使用Ajax发送用户消息到模拟后端 接收并显示智能回复 添加加载状态和错误处理

下面是完整代码实现:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能对话机器人</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            width: 100%;
            max-width: 800px;
            background-color: white;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            display: flex;
            flex-direction: column;
            height: 90vh;
        }

        .header {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }

        .header h1 {
            font-size: 1.8rem;
            margin-bottom: 5px;
        }

        .header p {
            opacity: 0.9;
            font-size: 0.95rem;
        }

        .chat-container {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .message {
            max-width: 80%;
            padding: 12px 18px;
            border-radius: 18px;
            position: relative;
            animation: fadeIn 0.3s ease-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .user-message {
            align-self: flex-end;
            background-color: #007bff;
            color: white;
            border-bottom-right-radius: 5px;
        }

        .bot-message {
            align-self: flex-start;
            background-color: #f0f2f5;
            color: #333;
            border-bottom-left-radius: 5px;
        }

        .message-header {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
        }

        .bot-icon {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 8px;
            color: white;
            font-size: 14px;
        }

        .user-icon {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            background-color: #007bff;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 8px;
            color: white;
            font-size: 14px;
        }

        .message-sender {
            font-weight: 600;
            font-size: 0.85rem;
        }

        .message-time {
            font-size: 0.75rem;
            opacity: 0.7;
            margin-top: 5px;
            text-align: right;
        }

        .bot-message .message-time {
            text-align: left;
        }

        .typing-indicator {
            display: flex;
            align-items: center;
            padding: 10px 15px;
            background-color: #f0f2f5;
            border-radius: 18px;
            width: fit-content;
            border-bottom-left-radius: 5px;
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #999;
            margin: 0 3px;
            animation: typingAnimation 1.4s infinite ease-in-out;
        }

        .typing-dot:nth-child(1) { animation-delay: -0.32s; }
        .typing-dot:nth-child(2) { animation-delay: -0.16s; }

        @keyframes typingAnimation {
            0%, 80%, 100% { transform: translateY(0); }
            40% { transform: translateY(-10px); }
        }

        .input-container {
            display: flex;
            padding: 20px;
            border-top: 1px solid #eee;
            background-color: #f9f9f9;
        }

        #userInput {
            flex: 1;
            padding: 14px 18px;
            border: 2px solid #e1e5eb;
            border-radius: 25px;
            font-size: 1rem;
            outline: none;
            transition: border-color 0.3s;
        }

        #userInput:focus {
            border-color: #007bff;
        }

        #sendBtn {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            border: none;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            margin-left: 15px;
            cursor: pointer;
            font-size: 1.2rem;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        #sendBtn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(106, 17, 203, 0.3);
        }

        #sendBtn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .welcome-message {
            text-align: center;
            padding: 30px 20px;
            color: #666;
        }

        .welcome-message h3 {
            color: #6a11cb;
            margin-bottom: 10px;
        }

        .suggestions {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 15px;
            justify-content: center;
        }

        .suggestion-btn {
            background-color: #f0f2f5;
            border: none;
            border-radius: 20px;
            padding: 8px 16px;
            font-size: 0.9rem;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .suggestion-btn:hover {
            background-color: #e1e5eb;
        }

        .error-message {
            background-color: #ffeaea;
            color: #d32f2f;
            border-left: 4px solid #d32f2f;
            padding: 12px 15px;
            border-radius: 0 8px 8px 0;
            margin: 10px 0;
            font-size: 0.9rem;
        }

        @media (max-width: 600px) {
            .container {
                height: 95vh;
                border-radius: 10px;
            }

            .message {
                max-width: 90%;
            }

            .header h1 {
                font-size: 1.5rem;
            }

            .suggestions {
                flex-direction: column;
                align-items: center;
            }

            .suggestion-btn {
                width: 100%;
                max-width: 300px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-robot"></i> 智能对话助手</h1>
            <p>基于Ajax技术的智能对话示例,点击下方按钮或输入问题开始对话</p>
        </div>

        <div class="chat-container" id="chatContainer">
            <div class="welcome-message">
                <h3>您好!我是智能助手</h3>
                <p>我可以回答各种问题,例如技术问题、生活建议等。您可以输入问题或点击下方建议问题开始对话。</p>
                <div class="suggestions">
                    <button class="suggestion-btn" data-question="JavaScript中Ajax是什么?">Ajax是什么?</button>
                    <button class="suggestion-btn" data-question="如何学习编程?">如何学习编程?</button>
                    <button class="suggestion-btn" data-question="介绍一下人工智能">人工智能介绍</button>
                    <button class="suggestion-btn" data-question="今天的天气怎么样?">天气查询</button>
                </div>
            </div>
        </div>

        <div class="input-container">
            <input type="text" id="userInput" placeholder="输入您的问题... (按Enter发送)" autocomplete="off">
            <button id="sendBtn">
                <i class="fas fa-paper-plane"></i>
            </button>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const chatContainer = document.getElementById('chatContainer');
            const userInput = document.getElementById('userInput');
            const sendBtn = document.getElementById('sendBtn');
            const suggestionBtns = document.querySelectorAll('.suggestion-btn');

            // 模拟的API端点 - 实际项目中应替换为真实后端API
            const API_URL = 'https://jsonplaceholder.typicode.com/posts';

            // 智能回复模拟数据
            const responses = {
                "ajax": "Ajax(Asynchronous JavaScript and XML)是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,Ajax可以使网页实现异步更新,这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。",
                "编程学习": "学习编程的建议:1. 选择一门合适的入门语言(如Python、JavaScript);2. 理解基本概念(变量、循环、函数等);3. 通过实际项目练习;4. 阅读他人代码;5. 参与开源项目;6. 坚持每天编码。",
                "人工智能": "人工智能(AI)是计算机科学的一个分支,致力于创建能够执行通常需要人类智能的任务的机器。这些任务包括视觉感知、语音识别、决策和语言翻译等。现代AI包括机器学习、深度学习和自然语言处理等领域。",
                "天气": "我是一个在线助手,无法获取实时天气数据。但您可以告诉我您所在的城市,我可以提供一般性的天气建议或指导您如何使用天气API获取实时信息。",
                "默认": "我已经理解了您的问题。虽然我无法访问实时数据或执行外部操作,但我可以为您提供相关信息、解释概念或协助您解决问题。请告诉我更多细节,我会尽力提供帮助。"
            };

            // 获取当前时间
            function getCurrentTime() {
                const now = new Date();
                return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
            }

            // 添加消息到聊天界面
            function addMessage(sender, text, isBot = false) {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${isBot ? 'bot-message' : 'user-message'}`;

                const messageHeader = document.createElement('div');
                messageHeader.className = 'message-header';

                const iconDiv = document.createElement('div');
                iconDiv.className = isBot ? 'bot-icon' : 'user-icon';
                iconDiv.innerHTML = isBot ? '<i class="fas fa-robot"></i>' : '<i class="fas fa-user"></i>';

                const senderSpan = document.createElement('span');
                senderSpan.className = 'message-sender';
                senderSpan.textContent = isBot ? '智能助手' : '您';

                messageHeader.appendChild(iconDiv);
                messageHeader.appendChild(senderSpan);

                const textDiv = document.createElement('div');
                textDiv.className = 'message-text';
                textDiv.textContent = text;

                const timeDiv = document.createElement('div');
                timeDiv.className = 'message-time';
                timeDiv.textContent = getCurrentTime();

                messageDiv.appendChild(messageHeader);
                messageDiv.appendChild(textDiv);
                messageDiv.appendChild(timeDiv);

                chatContainer.appendChild(messageDiv);
                chatContainer.scrollTop = chatContainer.scrollHeight;
            }

            // 显示正在输入指示器
            function showTypingIndicator() {
                const typingDiv = document.createElement('div');
                typingDiv.className = 'typing-indicator';
                typingDiv.id = 'typingIndicator';

                for (let i = 0; i < 3; i++) {
                    const dot = document.createElement('div');
                    dot.className = 'typing-dot';
                    typingDiv.appendChild(dot);
                }

                chatContainer.appendChild(typingDiv);
                chatContainer.scrollTop = chatContainer.scrollHeight;
            }

            // 隐藏正在输入指示器
            function hideTypingIndicator() {
                const typingIndicator = document.getElementById('typingIndicator');
                if (typingIndicator) {
                    typingIndicator.remove();
                }
            }

            // 显示错误消息
            function showError(message) {
                const errorDiv = document.createElement('div');
                errorDiv.className = 'error-message';
                errorDiv.innerHTML = `<i class="fas fa-exclamation-circle"></i> ${message}`;
                chatContainer.appendChild(errorDiv);
                chatContainer.scrollTop = chatContainer.scrollHeight;

                // 5秒后自动移除错误消息
                setTimeout(() => {
                    if (errorDiv.parentNode) {
                        errorDiv.remove();
                    }
                }, 5000);
            }

            // 模拟API调用获取智能回复
            function getBotResponse(userMessage) {
                // 在实际项目中,这里应该是真正的API调用
                // 这里我们使用setTimeout模拟网络延迟
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        // 模拟随机网络错误
                        if (Math.random() < 0.05) {
                            reject("网络请求失败,请检查连接后重试");
                            return;
                        }

                        // 根据关键词匹配回复
                        let responseText = responses["默认"];
                        const lowerCaseMessage = userMessage.toLowerCase();

                        if (lowerCaseMessage.includes("ajax")) {
                            responseText = responses["ajax"];
                        } else if (lowerCaseMessage.includes("编程") || lowerCaseMessage.includes("学习代码")) {
                            responseText = responses["编程学习"];
                        } else if (lowerCaseMessage.includes("人工智能") || lowerCaseMessage.includes("ai")) {
                            responseText = responses["人工智能"];
                        } else if (lowerCaseMessage.includes("天气")) {
                            responseText = responses["天气"];
                        }

                        // 在实际项目中,这里应该是真实的API响应
                        // 模拟API响应结构
                        const mockResponse = {
                            id: Date.now(),
                            title: "智能回复",
                            body: responseText,
                            userId: 1
                        };

                        resolve(mockResponse);
                    }, 800 + Math.random() * 1200); // 随机延迟800-2000ms模拟网络请求
                });
            }

            // 处理发送消息
            async function sendMessage() {
                const message = userInput.value.trim();

                if (!message) {
                    userInput.focus();
                    return;
                }

                // 禁用输入和按钮
                userInput.disabled = true;
                sendBtn.disabled = true;

                // 添加用户消息到聊天界面
                addMessage('user', message, false);

                // 清空输入框
                userInput.value = '';

                // 显示"正在输入"指示器
                showTypingIndicator();

                try {
                    // 使用Ajax获取回复
                    const response = await getBotResponse(message);

                    // 隐藏"正在输入"指示器
                    hideTypingIndicator();

                    // 添加机器人回复到聊天界面
                    addMessage('bot', response.body, true);

                } catch (error) {
                    // 隐藏"正在输入"指示器
                    hideTypingIndicator();

                    // 显示错误消息
                    showError(error);

                    // 添加一个默认回复
                    addMessage('bot', "抱歉,我遇到了一些技术问题。不过我可以告诉您:Ajax是一种用于创建异步Web应用的技术。", true);
                } finally {
                    // 重新启用输入和按钮
                    userInput.disabled = false;
                    sendBtn.disabled = false;
                    userInput.focus();
                }
            }

            // 事件监听
            sendBtn.addEventListener('click', sendMessage);

            userInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !sendBtn.disabled) {
                    sendMessage();
                }
            });

            // 建议问题按钮点击事件
            suggestionBtns.forEach(btn => {
                btn.addEventListener('click', function() {
                    const question = this.getAttribute('data-question');
                    userInput.value = question;
                    userInput.focus();
                });
            });

            // 添加初始机器人问候
            setTimeout(() => {
                addMessage('bot', '您好!我是智能助手,随时准备回答您的问题。', true);
            }, 1000);
        });
    </script>
</body>
</html>

功能说明

聊天界面

Ajax交互

智能回复逻辑

用户体验

使用说明

直接在输入框中输入问题并按Enter或点击发送按钮 点击建议问题按钮快速提问 观察机器人的智能回复

您可以将此代码保存为HTML文件并在浏览器中直接打开使用。在实际项目中,您需要将模拟的API调用替换为真实的后端API接口。

相关推荐