我正在使用 JQuery/JS 和 Django Channels WebSockets 来配置聊天消息的实时通知。
当用户有任何带有 nofication_read=False
的 Notification
对象时,它们会使用下面的代码在导航栏中呈现。
{{ notification|length }}
显示带有 nofication_read=False
的 Notification
对象的数量。
导航栏.html
<li id="notification_li" class="nav-item">
<a class="nav-link" href="#" id="notificationLink">
<span id="notification_id{{notification_id}}">{{ notification|length }}</span>
<div id="notificationContainer">
<div id="notificationTitle">Notifications</div>
<div id="notificationsBody" class="notifications">
{% for notifications in notification|slice:"0:10" %}
<span id="notification-{{notification.id}}">
{{ notifications.notification_chat.message }}
via {{ notifications.notification_chat.user }}
at {{ notifications.notification_chat.timestamp }}
</span>
{% endfor %}
我知道目前这不是实时的。
但问题是,当用户刷新页面并点击红色图标span id=notification_id
显示他们的未读通知列表时,数据是通过websocket发送的( JSON.stringify
) 作为 "type": "notification_read"
调用 if message_type == "notification_read":
命令在 consumers.y
在数据库中将它们标记为 nofication_read=True
。
当用户刷新页面时,红色图标不再存在,当他们尝试点击背景链接时,浏览器控制台出现错误无法点击
Uncaught ReferenceError: notification_id is not defined
一旦他们收到另一个通知并且页面被刷新,它显然会再次变得可点击。
在初始点击后的任何时候,用户仍然应该能够点击并查看已读
通知列表。
消费者.py
class ChatConsumer(AsyncConsumer):
...
async def websocket_receive(self, event):
message_type = json.loads(event.get('text','{}')).get('type')
if message_type == "notification_read":
user = self.scope['user']
username = user.username if user.is_authenticated else 'default'
# Update the notification read status flag in Notification model.
notification = Notification.objects.filter(notification_user=user).update(notification_read=True)
print("notification read")
return
front_text = event.get('text', None)
if front_text is not None:
loaded_dict_data = json.loads(front_text)
msg = loaded_dict_data.get('message')
user = self.scope['user']
username = user.username if user.is_authenticated else 'default'
notification_id = 'default'
myResponse = {
'message': msg,
'username': username,
'notification': notification_id,
}
...
await self.create_chat_message(user, msg)
other_user = self.scope['url_route']['kwargs']['username']
other_user = User.objects.get(username=other_user)
await self.create_notification(other_user, msg)
...
@database_sync_to_async
def create_chat_message(self, me, msg):
thread_obj = self.thread_obj
return ChatMessage.objects.create(thread=thread_obj, user=me, message=msg)
@database_sync_to_async
def create_notification(self, other_user, msg):
last_chat = ChatMessage.objects.latest('id')
created_notification = Notification.objects.create(notification_user=other_user, notification_chat=last_chat)
return created_notification
上下文处理器.py
def notification(request):
if request.user.is_authenticated:
notification = Notification.objects.filter(notification_user=request.user, notification_read=False)
return {
'notification':notification,
return Notification.objects.none()
基础.html
<script>
$(document).ready(function() {
$("#notificationLink").click(function() {
var data = {
"type": "notification_read",
"username": username,
"notification_id": notification_id,
}
socket.send(JSON.stringify(data));
$("#notificationContainer").fadeToggle(300);
$("#notification_id").fadeOut("slow");
return false;
});
...
var incomingMsg = $('.incoming_msg')
socket.onmessage = function(e) {
console.log("message", e)
var chatDataMsg = JSON.parse(e.data)
incomingMsg.append('<li>' + chatDataMsg.message + ' from ' + chatDataMsg.username + '</li>')
}
最佳答案
在"notification_id": notification_id
之前你应该定义notification_id
,但在你的情况下你需要通过循环来做,你可以尝试:
$("#notificationLink").click(function() {
$('span[id^="notification-"]').each(function(){
var notification_id = $(this).attr('id').substring(13)
var data = {
"type": "notification_read",
"username": username,
"notification_id": notification_id,
}
socket.send(JSON.stringify(data));
});
$("#notificationContainer").fadeToggle(300);
$("#notification_id").fadeOut("slow");
return false;
})
我希望你的模板中已经有类似的东西:
var username = '{{ request.user.username }}'
根据后端的当前代码,您不需要 notification_id
,因此您可以简单地将其删除:
$("#notificationLink").click(function() {
var data = {
"type": "notification_read",
"username": username,
}
socket.send(JSON.stringify(data));
$("#notificationContainer").fadeToggle(300);
$("#notification_id").fadeOut("slow");
return false;
});
关于javascript - 通知不可点击一次 "read": error "notification_id is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55971636/