css 每次按下发送消息按钮后,聊天机器人窗口都会关闭

lymgl2op  于 2022-12-24  发布在  其他
关注(0)|答案(1)|浏览(100)

我正在尝试为我的Django应用程序构建一个聊天机器人。基于这个tutorial,我做了下面的javascript和html。问题是在发送每一条消息后(按下发送按钮),聊天机器人窗口被关闭。2通常它应该在讨论结束后才关闭。3我不确定发生了什么。4我尝试使用防止默认事件方法(不确定我是否正确),问题仍然存在。

class Chatbox {
  constructor() {
        this.args = {
            openButton: document.querySelector('.chatbox__button'),
            chatBox: document.querySelector('.chatbox__support'),
            sendButton: document.querySelector('.send__button')
        }

        this.state = false;
        this.messages = [];
    }
  display() {

    
      const {openButton, chatBox, sendButton} = this.args;

        openButton.addEventListener('click', () => this.toggleState(chatBox))

        sendButton.addEventListener('click', () => this.onSendButton(chatBox))

        const node = chatBox.querySelector('input');
        node.addEventListener("keyup", ({key}) => {
            if (key === "Enter") {
                this.onSendButton(chatBox)
            }
        })
    }

  
    toggleState(chatbox) {
        this.state = !this.state;

        // show or hides the box
        if(this.state) {
            chatbox.classList.add('chatbox--active')
        } else {
            chatbox.classList.remove('chatbox--active')
        }
    }

  onSendButton(chatbox) {
        var textField = chatbox.querySelector('input');
        let text1 = textField.value
        if (text1 === "") {
            return;
        }

        let msg1 = { name: "User", message: text1 }
        this.messages.push(msg1);

        fetch('/chatbot', {
            method: 'POST',
            body: JSON.stringify({ message: text1 }),
            headers: {'X-CSRFToken': Cookies.get('csrftoken')},
            mode: 'same-origin' //
          })
          .then(r => r.json())
          .then(r => {
            let msg2 = { name: "Sam", message: r.answer };
            this.messages.push(msg2);
            console.log("msg2")
            this.updateChatText(chatbox)
            console.log("updated chat text")
            textField.value = ''

        }).catch((error) => {
            console.error('Error:', error);
            this.updateChatText(chatbox)
            textField.value = ''
          });
    }

  updateChatText(chatbox) {
    
    let html = '';
        this.messages.slice().reverse().forEach(function(item, index) {
            if (item.name === "Sam")
            {
                html += '<div class="messages__item messages__item--visitor">' + item.message + '</div>'
            }
            else
            {
                html += '<div class="messages__item messages__item--operator">' + item.message + '</div>'
            }
          });
    
    const chatMessages = chatbox.querySelector('.chatbox__messages');
    chatMessages.innerHTML = html + chatMessages.innerHTML;
   // chatMessages.innerHTML = html;
  }

}

const chatbox = new Chatbox();
chatbox.display();

下面是html:

{% load static %}
<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="{% static 'css/bot.css' %}">

<head>
    <meta charset="UTF-8">

    <title>Chatbot</title>

    
</head>
<body>
<div class="container">
    <div class="chatbox">

        <div class="chatbox__support">
            <div class="chatbox__header">
                <div class="chatbox__image--header">
                    <img src="https://files.softicons.com/download/social-media-icons/free-social-media-icons-by-uiconstock/png/48x48/Reddit-Icon.png" alt="image">
                </div>
                <div class="chatbox__content--header">
                    <h4 class="chatbox__heading--header">Chat support</h4>
                    <p class="chatbox__description--header">Hi. My name is Sam. How can I help you?</p>
                </div>
               
            </div>
           

           
            <div class="chatbox__messages">
               {% for message, response,timestamp in chat_history %}
                   
                    <!-- Response -->
                    {% if response %}
                    <div class="messages__item messages__item--visitor">

                        {{ response }}
                        
                    </div>
                     <!-- Message -->
                    <div class="messages__item {% if response %}messages__item--operator{% else %}messages__item--{% endif %}">
                     {{ message }}
                    </div>

                    {% endif %}
                {% endfor %}
               
            </div>
            <div class="chatbox__footer">
                
                <form method="post" action="{% url 'chatbot' %}">
                   {% csrf_token %}
                    <!-- Input -->
                    <input type="text" name="message"  class="input" placeholder="Type your message here..."> 

                    
                    <button type="submit" class="chatbox__send__footer send__button" >Send</button>
                </form>  
            </div>
        </div>
        <div class="chatbox__button">
            <button><img src="https://raw.githubusercontent.com/patrickloeber/chatbot-deployment/ce309f3aae1ccc3783059876a1b66e4d7d77ca9f/standalone-frontend/images/chatbox-icon.svg" /></button>
        </div>
    </div>
</div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<script type="text/javascript" src="{% static 'js/bot.js' %}"></script>
</body>
</html>

在控制台中,错误消息为:注:

bot.js:69:21 from this line: console.error('Error:', error);
Error: TypeError: NetworkError when attempting to fetch resource.
    onSendButton http://127.0.0.1:8000/static/js/bot.js:69
    (Async: promise callback)
    onSendButton http://127.0.0.1:8000/static/js/bot.js:68
    display http://127.0.0.1:8000/static/js/bot.js:19
    (Async: EventListener.handleEvent)
    display http://127.0.0.1:8000/static/js/bot.js:19
    <anonymous> http://127.0.0.1:8000/static/js/bot.js:99

有什么主意吗?谢谢!

6yt4nkrj

6yt4nkrj1#

我不知道为什么会出现这个错误,但我已经能够在我的机器上重现这个错误,而且修复很简单。将您的按钮更改为键入button而不是submit:

<button type="button" class="chatbox__send__footer send__button" >Send</button>

当按钮类型为submit时,它会尝试通过正常路径发送表单,但您希望JavaScript来处理它。如果您有submit事件侦听器,则可以使用preventDefault()来防止按钮导致表单以正常的默认方式提交。
按照您现在的方式,按钮既尝试将表单发送到正常路径 *,JavaScript也尝试处理事件,我 * 认为 * 这就是导致问题的原因。
您可以将按钮类型保留为submit,然后通过为按钮指定一个id来使用preventDefault():

<button id="send__button" type="submit" class="chatbox__send__footer send__button" >Send</button>

然后把这个加到你的脚本里,在聊天室之外

document.getElementById('send__button').addEventListener('click', (e) => {
          e.preventDefault();
        });

相关问题