首页 > 解决方案 > JQuery .append() 到单个 forloop Python Django 中的多个位置

问题描述

我有一个聊天应用程序,消息被归类为outgoingincoming

在客户端,这些消息显示在聊天的任一侧,具体取决于它们是发送还是接收。

例子

我正在尝试使用 Jquery.append(msgText)在发送或接收消息时回显消息(如上图所示),但无法以正确的格式在正确的位置回显(它仅在页面刷新后显示,但我想要它实时回显)。

我已经尝试在 forloop 中var sentMsg = $('#sent_msg')使用#sent_msgas id 作为目标,但它显然只是将发送的文本附加到每条发送的消息中。

如果我把它放在 forloop (ex) 之外var chatHolder = $('#chat-items'),那么问题是左侧和右侧没有格式......所有消息(发送和接收)都只是在无序列表的左侧出现.

有没有办法附加到 forloop 的每个新迭代并应用正确的格式/样式?

我在这里学习绳索,因此将不胜感激任何输入。

线程.html

 <ul id="chat-items">
            {% for chat in object.chatmessage_set.all %}
            {% if chat.user == user %}
<div id="sent_msg">
            <div class="outgoing_msg">
              <div class="outgoing_msg_img"> <img src="{{ chat.user.profile.image.url }}" alt="sunil"> </div>
              <div class="sent_msg">
                <p>{{ chat.message }}</p>
                <span class="time_date"> {{ chat.timestamp }}</span>
              </div>
            </div>
</div>
            {% else %}
<div id="incoming_msg">
            <div class="incoming_msg">
              <div class="incoming_msg_img"> <img src="{{ chat.user.profile.image.url }}" alt="sunil"> </div>
              <div class="received_msg">
                <div class="received_withd_msg">
                  <p>{{ chat.message }}</p>
                  <span class="time_date"> {{ chat.timestamp }}</span>
                </div>
              </div>
            </div>
</div>
            {% endif %}
            {% endfor %}
            </ul>

base.html

<script>
    // websocket scripts - client side*
    var loc = window.location
    var msgInput = $("#id_message")
    var chatHolder = $('#chat-items')
    var incomingMsg = $('#incoming_msg')
    var sentMsg = $('#sent_msg')

    // below is the message I am receiving
    socket.onmessage = function(e) {
      console.log("message", e)
      var chatDataMsg = JSON.parse(e.data)
      incomingMsg.append('<li>' + chatDataMsg.message + ' from ' + chatDataMsg.username + '</li>')
    }

    // below is the message I am sending
    socket.onopen = function(e) {
      console.log("open", e)
      formData.submit(function(event) {
        event.preventDefault()
        var msgText = msgInput.val()
        sentMsg.append(msgText)
        var finalData = {
          'message': msgText
        }
        socket.send(JSON.stringify(finalData))
        formData[0].reset()
      })
    }

结果

标签: pythonjquerydjango

解决方案


推荐阅读