python - JQuery .append() 到单个 forloop Python Django 中的多个位置
问题描述
我有一个聊天应用程序,消息被归类为outgoing
或incoming
。
在客户端,这些消息显示在聊天的任一侧,具体取决于它们是发送还是接收。
我正在尝试使用 Jquery.append(msgText)
在发送或接收消息时回显消息(如上图所示),但无法以正确的格式在正确的位置回显(它仅在页面刷新后显示,但我想要它实时回显)。
我已经尝试在 forloop 中var sentMsg = $('#sent_msg')
使用#sent_msg
as 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()
})
}
解决方案
推荐阅读
- r - 如何在r中一个接一个地聚合数据?
- javascript - Javascript:如何使用取自不同目录的唯一 URL
- bash - 詹金斯管道 - 出错时转到 postFailure 块
- twilio - Twilio - SMS 用非 twilio 号码掩盖我的 twilio 号码(来自)
- r - 如何在 R 中求解非线性方程
- docker - 从 ansible docker_container 到 community.general.docker_container 的变化
- python - 获取连续第一个空单元格值
- python - 尝试返回包含子字符串 python 的所有嵌套 json 字典值
- python - 如何修复不收听/接受信息的 python 套接字?
- python - 在 Python 中为多键字典赋值?